如何编写比较器以将列表的所有元素与输入进行比较并移动到顶部
How to write a comparator to compare all the elements of a list to a input and move to top
我有一个列表
List<String> myList = Arrays.asList("1234", "1214", "1334");
我的输入是:
String mInput = "1214"
如何写一个比较器来比较myList
和mInput
的所有元素,如果相等,则将其移动到列表的顶部
您不需要可以使用的比较器:
List<String> myList = new ArrayList<>(Arrays.asList("1234", "1214", "1334"));
String mInput = "1214";
if (myList.contains(mInput)) {
myList.remove(mInput);// remove mInput
myList.add(0, mInput);// add it to to index 0 (top of list)
}
System.out.println(myList);// Input [1214, 1234, 1334]
注意你必须使用new ArrayList<>(Arrays.asList("1234", "1214", "1334"))
来理解为什么,你可以阅读这个UnsupportedOperationException when trying to remove from the list returned by Array.asList
如果你真的需要这里的比较器,你可以这样做(假设mInput
不是null
):
myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));
你可以自己写Comparator
:
class BringToFrontComparator<T extends Comparable<T>> implements Comparator<T> {
T front;
public BringToFrontComparator(T front) {
this.front = front;
}
@Override
public int compare(T o1, T o2) {
return o1.equals(front) && !o2.equals(front)
// Front one is always less than anything other than itself.
? -1
// Normal comparison elsewhere.
: o1.compareTo(o2);
}
}
public void test(String[] args) throws Exception {
List<String> myList = Arrays.asList("1234", "1214", "1334");
String mInput = "1334";
Collections.sort(myList, new BringToFrontComparator<>(mInput));
System.out.println(myList);
}
打印
[1334, 1214, 1234]
我有一个列表
List<String> myList = Arrays.asList("1234", "1214", "1334");
我的输入是:
String mInput = "1214"
如何写一个比较器来比较myList
和mInput
的所有元素,如果相等,则将其移动到列表的顶部
您不需要可以使用的比较器:
List<String> myList = new ArrayList<>(Arrays.asList("1234", "1214", "1334"));
String mInput = "1214";
if (myList.contains(mInput)) {
myList.remove(mInput);// remove mInput
myList.add(0, mInput);// add it to to index 0 (top of list)
}
System.out.println(myList);// Input [1214, 1234, 1334]
注意你必须使用new ArrayList<>(Arrays.asList("1234", "1214", "1334"))
来理解为什么,你可以阅读这个UnsupportedOperationException when trying to remove from the list returned by Array.asList
如果你真的需要这里的比较器,你可以这样做(假设mInput
不是null
):
myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));
你可以自己写Comparator
:
class BringToFrontComparator<T extends Comparable<T>> implements Comparator<T> {
T front;
public BringToFrontComparator(T front) {
this.front = front;
}
@Override
public int compare(T o1, T o2) {
return o1.equals(front) && !o2.equals(front)
// Front one is always less than anything other than itself.
? -1
// Normal comparison elsewhere.
: o1.compareTo(o2);
}
}
public void test(String[] args) throws Exception {
List<String> myList = Arrays.asList("1234", "1214", "1334");
String mInput = "1334";
Collections.sort(myList, new BringToFrontComparator<>(mInput));
System.out.println(myList);
}
打印
[1334, 1214, 1234]