sorting List<Class> by one of its variable

java

Solution

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)

Problem

I have a Class1 ``` public class Class1 { public Class(String s, int[] s1, int soc) { this.s = s; this.s1 = s1; this.soc = soc } } ``` I have a `List` of `Class1` (`List<Class1>`). I want to sort this list by `soc`, to get the `Class1` with highest `soc` first

Original source

Related problems