Issue
Suppose I have 2 lists:
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(2,1,3);
Is there a short way, using streams, to "sort" list1 as list2? Currently I can do it only using loops and regular comparisons.
Solution
Something like this could do the trick.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class Scratch {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(2,1,3);
list1.sort(Comparator.comparing(list2::indexOf));
System.out.println(list1);
}
}
Idea is simple, to compare things you have to set them values that express their "rank". Here, the rank is simply the index of that value in list2.
An element in list1 but not in list2 would get the rank -1 and would be in the first elements, not sure how they would be sorted together thought. An element in list2 but not in list1 would just not alter the sorting.
EDIT :
To get an example if the value is encapsulated in another object (see comments of OP), it would be something like :
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class MyObject {
private int value;
public MyObject(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return "MyObject{" +
"value=" + value +
'}';
}
}
class Scratch {
public static void main(String[] args) {
List<MyObject> list1 = Arrays.asList(withValue(1),withValue(2),withValue(3));
List<Integer> list2 = Arrays.asList(2,1,3);
list1.sort(Comparator.comparing(mo -> list2.indexOf(mo.getValue())));
System.out.println(list1);
}
public static MyObject withValue(int i){
return new MyObject(i);
}
}
Answered By - Jonathan Schoreels