Sort List <Class> by one of its variables
Use 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 comparison method returns -1 for "the first argument comes first in the sorted list", 0 for "they are equally ordered", and 1 for "the first argument takes second place in the sorted list", and the list is changed 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")); } } He 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 own sort method, and then pass an instance of this class to this function: Collections.sort
While Scott Stanfield's answer is usually the easiest way to do this in Java at the moment, if you have other functional things that you might want to do with the properties of your class, it might be useful to use Guava Function s.
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 the Ordering class to sort:
List<Class1> list = ...; Collections.sort(list, Ordering.natural().reverse().onResultOf(Class1.GET_SOC)); This uses the inverse sequence of natural ordering based on the soc property for each instance of Class1 to provide the desired order.