I have an issue with sorting an Array List. In a class i have two Array Lists of different objects, we can call the objects Foo and Bar.
public class Foo() {
int value;
//Some other fields, and setters and getters.
}
public class Bar() {
int id;
//Same here...
}
So the list fooList can be totally scrambeled. Say that i have 16 Foos, but Foo with value 5 can be on index 13 and so on.
What i'm trying to do is to order barList to match fooList after these values. If Foo with value 5 is on index 13, i want Bar with value 5 to be on index 13. My last attempt was this, but no success.
HashMap<Integer, Integer> positions = new HashMap<>();
for(int i=0;i<fooList.size();i++){
positions.put(foo.get(i).getValue, i);
}
Collections.sort(barList, new Comparator<Bar>(){
public int compare(Bar obj1, Bar obj2){
return positions.get(barList.indexOf(obj1)) -
positions.get(barList.indexOf(obj2));
}
});
Does anybody have a clue how to do this in an efficient way?
FooBar. It holds a reference to aFooand another to aBar. It is comparable with otherFooBarinstances based on your criteria.positions.get( obj1.getId() )?