Reputation: 2721
I use a linkedlist in my java program, and the element is a custom type which has three fields, one of them is of Integer type. My problem is: how to sort the linkedlist according the value of the Integer filed?
Upvotes: 2
Views: 15167
Reputation: 10487
You can use a Comparator which knows how to sort your Objects like this:
public class Foo {
public String ignoreMe;
public int sortOnMe;
public Object ignoreMeToo;
public static void main() {
final List<Foo> unsorted = new LinkedList<Foo>();
// add elements...
Collections.sort(unsorted, new Comparator<Foo>() {
@Override
public int compare(Foo o1, Foo o2) {
return o1.sortOnMe < o2.sortOnMe ? -1 : o1.sortOnMe == o2.sortOnMe ? 0 : 1;
}
});
}
}
Upvotes: 3
Reputation: 422
You can use the Collections.sort method with a custom Comparator.
Collections.sort(your_list, new Comparator<YoureValueType>(){
@Override
public int compare(YoureValueType o1, YoureValueType o2){
if(o1.getMagicInt() < o2.getMagicInt()){
return -1;
}
if(o1.getMagicInt() > o2.getMagicInt()){
return 1;
}
return 0;
}
});
Edit: I just saw Alexandr comment about very large and small values on waldheinz answer. I updated my code to reflect his argument.
Upvotes: 9
Reputation: 954
Simply write a class that implements Comparator-Interface.
Than use Collections.sort(list, comparator) to sort your List.
For more informations read this tutorial
Upvotes: 1