I have a List
List<String> myList = Arrays.asList("1234", "1214", "1334");
My input is:
String mInput = "1214"
How to write a comparator to compare all the elements of myList
to mInput
and if it is equal, move it to the top of the list
I have a List
List<String> myList = Arrays.asList("1234", "1214", "1334");
My input is:
String mInput = "1214"
How to write a comparator to compare all the elements of myList
to mInput
and if it is equal, move it to the top of the list
You can write your own 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);
}
prints
[1334, 1214, 1234]
You don't need a comparator you can use :
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]
Note you have to use new ArrayList<>(Arrays.asList("1234", "1214", "1334"))
to understand why, you can read this UnsupportedOperationException when trying to remove from the list returned by Array.asList
If you really need comparator here, you can do something like this (assuming that mInput
is not null
):
myList.sort((String o1, String o2) -> mInput.equals(o1) && !mInput.equals(o2) ? -1 : o1.compareTo(o2));