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")); } }); 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")); } }); 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.
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(); } null and will throw an NPE. - Nofate ♦Source: https://ru.stackoverflow.com/questions/565291/
All Articles