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?
Asked
Active
Viewed 1.5k times
2
-
possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – krlmlr May 31 '13 at 17:54
4 Answers
9
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.

tfk
- 402
- 3
- 9
3
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;
}
});
}
}

Waldheinz
- 10,399
- 3
- 31
- 61
-
2this code may give the wrong answer when there is overflow. For instance, when comparing a large negative value to a large positive value, the difference may be more than the largest value that can be stored in an integer, Integer.MAX_VALUE. – Alexandr Jun 16 '11 at 09:47
-
public int compare(Foo o1, Foo o2) { return o1.sortOnMe < o2.sortOnMe ? -1 : o1.sortOnMe == o2.sortOnMe ? 0 : 1 ; } – Alexandr Jun 16 '11 at 09:48
-
@Alexandr You are right. Fixed it. I think I have to look through some code I wrote in the past 10 years or so now. Oh my... – Waldheinz Jun 16 '11 at 10:07
1
1
Simply write a class that implements Comparator-Interface.
Than use Collections.sort(list, comparator) to sort your List.
For more informations read this tutorial

CSan
- 954
- 1
- 10
- 25