Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting List<Class> by one of its variable

Tags:

java

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

like image 223
y2p Avatar asked Oct 25 '10 19:10

y2p


1 Answers

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)

like image 124
Scott Stanchfield Avatar answered Sep 20 '22 12:09

Scott Stanchfield