I have two ArrayLists
A: 5 3 2 6 1 4
B: 0 1 2 0 3 2
I want to sort B, based on corresponding values from A, so I should get : 3 2 1 2 0 0
When I use the following codes :
ArrayList<Integer> D=new ArrayList<Integer>(B);
Collections.sort(B, Comparator.comparing(s -> A.get(D.indexOf(s))));
or :
ArrayList<Integer> D = new ArrayList<Integer>(B);
Collections.sort(B, new Comparator<Integer>(){
public int compare(Integer a,Integer b){
return Integer.compare(A.get(D.indexOf(a)),A.get(D.indexOf(b)));
}
});
It would have worked if the elements in B were unique, but since both 2 and 0 has 2 occurances, every time A.get(D.indexOf(2)) is called, 2 is returned and 4 is never returned.
So I finally get : 3 2 2 1 0 0
Can anyone help me with a comparator that deals with this? I don't want to make a full sorting algorithm, but such solutions are also welcome.