Reputation: 7429
I have an array with ids
[2,3,1]
From an external rest Service, I'll get a List with UserObjects. These userObjects contains userids (1 or 2 or 3)
I now would like to sort the list in the same order, The userids appear in my array. Maybe it's helpful to say that I am able to use guava (v15) in my code. Thanks.
Upvotes: 0
Views: 316
Reputation: 47280
Arrays.sort is your friend : http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(short[])
Or if you want to sort a collection of complex types, make sure the complex type (user?) implements comparable and compareTo.
Or more likely in this, you'll need to supply a custom comparator, which allows sorting by in different orders like this.
Upvotes: 0
Reputation: 10342
You can use Collections.sort(List,Comparator), with a comparator like this:
class MyComp implements Comparator<UserObject> {
private int[] ref;
public MyComp(int [] reference) {
this.ref=reference;
}
public compare(UserObject o1, UserObjects o2) {
return Ints.indexOf(ref,o1.id) - Ints.indexOf(ref,o2.id);
}
}
Upvotes: 0
Reputation: 1271
int[] ids = ...
List<UserObject> userObjects = ...
Collections.sort(userObjects, new Comparator<UserObject>() {
public int compare(UserObject a, UserObject b) {
return Ints.compare(
Ints.indexOf(ids, a.getId()),
Ints.indexOf(ids, b.getId()));
}
});
Upvotes: 2