1

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Devrath
  • 42,072
  • 54
  • 195
  • 297

3 Answers3

3

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]

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
2

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

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));

Lennier
  • 125
  • 1
  • 9