java 如何将选中的项目移动到列表的顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5321463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:38:22  来源:igfitidea点击:

How to move the selected item to move to the top of the list

java

提问by user339108

List<String> strings; // contains "foo", "bar", "baz", "xyz"

and if given an input "baz"the function re-arrange(String input) should return the strings

如果给定一个输入"baz",函数 re-arrange(String input) 应该返回字符串

"baz", "foo", "bar", "xyz"

and if given an input "bar"the function re-arrange(String input) should return the strings

如果给定一个输入"bar",函数 re-arrange(String input) 应该返回字符串

"bar", "foo", "baz", "xyz"

回答by sstendal

First, remove the item and then add the item again at position 1.

首先,删除该项目,然后在位置 1 处再次添加该项目。

List<String> strings;

List<String> rearrange(String input) {
    strings.remove(input);
    strings.add(0,input);
    return strings;
}

回答by Mike Samuel

public static <T> List<T> rearrange(List<T> items, T input) {
  int index = items.indexOf(input);
  List<T> copy;
  if (index >= 0) {
    copy = new ArrayList<T>(items.size());
    copy.add(items.get(index));
    copy.addAll(items.subList(0, index));
    copy.addAll(items.subList(index + 1, items.size()));
  } else {
    return items;
  }
  return copy;
}

回答by Mines Valderama-Hababag Hernan

public static <T> void setTopItem(List<T> t, int position){
    t.add(0, t.remove(position));
}

回答by Navigateur

To move the original item to the top of the original list:

要将原始项目移动到原始列表的顶部:

public static <T> void rearrange(List<T> items, T input){
    int i = items.indexOf(input);
    if(i>=0){
        items.add(0, items.remove(i));
    }
}