How to add the second and third additional sorting condition?

Collections.sort(list, new Comparator<Stock>() { public int compare(Stock stock1, Stock stock2) { return ((String)stock1.get("name")).compareTo((String)stock2.get("name")); } }); 
  • is java 8 available? - zRrr
  • Yes, java 8 is available - Nikita Ryazan

2 answers 2

 public int compare(Stock stock1, Stock stock2) { int res = ((String)stock1.get("a")).compareTo((String)stock2.get("a")); return res != 0 ? ((String)stock1.get("b")).compareTo((String)stock2.get("b")) : res; } 

For several conditions:

 public int compare(Smth x, Smth y) { int res; if ((res = xacompareTo(ya)) != 0) return res; if ((res = xbcompareTo(yb)) != 0) return res; if ((res = xccompareTo(yc)) != 0) return res; if ((res = xdcompareTo(yd)) != 0) return res; if ((res = xecompareTo(ye)) != 0) return res; if ((res = xfcompareTo(yf)) != 0) return res; if ((res = xgcompareTo(yg)) != 0) return res; return xhcompareTo(yh); } 

PS: Unfortunately, as js will not work.

  • @zRrr, added the answer. - Qwertiy

Judging by en-SO , for Java 8 you can do this:

 Comparator.comparing((Person p)->p.firstName) .thenComparing(p->p.lastName) .thenComparingInt(p->p.age); 

Attention this method can throw NPE if one of the objects is null


To version 8, judging by Google, it is enough just to sort sequentially with various simple comparators


You can also connect to the Apache Commons library and do this:

 public int compare(Person a, Person b){ return new CompareToBuilder() .append(a.getName(), b.getName()) .append(a.getAddress(), b.getAddress()) .toComparison(); } 
  • Note that the comparator in the first example does not check for null and will throw an NPE. - Nofate
  • @Nofate, i.e. they don’t have checks inside? .. 0_o how is that ( - YuriySPb
  • @Nofate, hmm, yes, it’s written in the dock. Strange implementation. Added in reply - YuriySPb