sorting List<Class> by one of its variable
I have a Class1
public class Class1 {
public Class(String s, int[] s1, int soc) {
this.s = s;
this.s1 = s1;
this.soc = soc
}
}
开发者_C百科I have a List
of Class1
(List<Class1>
). I want to sort this list by soc
, to get the Class1
with highest soc
first
Use a Comparator
Collections.sort(list, new Comparator<Class1>() {
public int compare(Class1 c1, Class1 c2) {
if (c1.soc > c2.soc) return -1;
if (c1.soc < c2.soc) return 1;
return 0;
}});
(Note that the compare method returns -1 for "first argument comes first in the sorted list", 0 for "they're equally ordered" and 1 for the "first argument comes second in the sorted list", and the list is modified by the sort method)
Here is a complete example:
import java.util.*;
class Class1 {
String s;
int[] s1;
int soc;
public Class1(String s, int[] s1, int soc) {
this.s = s;
this.s1 = s1;
this.soc = soc;
}
public String toString() { return String.format("s: %s soc: %d", s, soc); }
}
public class Test {
public static void main(String... args) {
List<Class1> list = new ArrayList<Class1>();
list.add(new Class1("abcd", new int[] {1}, 3));
list.add(new Class1("efgh", new int[] {2}, 5));
list.add(new Class1("ijkl", new int[] {8}, 9));
list.add(new Class1("mnop", new int[] {3}, 7));
Collections.sort(list, new Comparator<Class1>() {
public int compare(Class1 o1, Class1 o2) {
return o1.soc > o2.soc ? -1 : o1.soc == o2.soc ? 0 : 1;
}
});
System.out.println(list.toString().replaceAll(",", "\n"));
}
}
It prints the following:
[s: ijkl soc: 9
s: mnop soc: 7
s: efgh soc: 5
s: abcd soc: 3]
Create a class that implements Comparator, create your custom sorting method and then pass an instance of that class into this function: Collections.sort
While Scott Stanchfield's answer is generally the easiest way to do this in Java currently, if you have other functional things you might want to do with properties of your class it can be useful to make use of Guava's Functions.
public class Class1 {
...
public static final Function<Class1, Integer> GET_SOC =
new Function<Class1, Integer>() {
public Integer apply(Class1 input) {
return input.soc;
}
};
...
}
Then you can use its Ordering class to sort:
List<Class1> list = ...;
Collections.sort(list, Ordering.natural().reverse().onResultOf(Class1.GET_SOC));
This uses the reverse of the natural ordering based on the soc
property of each Class1
instance to give the ordering you want.
精彩评论