Create a SortedMap in Java with a custom Comparator

You can use a custom comparator like this: Comparator<String> secondCharComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.substring(1, 2).compareTo(s2.substring(1, 2)); } }; Sample: SortedMap<String,String> map = new TreeMap<String,String>(secondCharComparator); map.put(“Za”, “FOO”); map.put(“Ab”, “BAR”); map.put(“00”, “ZERO”); System.out.println(map); // prints “{00=ZERO, Za=FOO, Ab=BAR}” Note that this simply assumes that the String has … Read more

Using a comparator function to sort

In Python 3 there is no cmp argument for the sorted function (nor for list.sort). According to the docs, the signature is now sorted(iterable, *, key=None, reverse=False), so you have to use a key function to do a custom sort. The docs suggest: Use functools.cmp_to_key() to convert an old-style cmp function to a key function. … Read more

Java – Sort Strings like Windows Explorer

This is my second try to answer this. I used http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting as a start. Unfortunatly I think I found there problems as well. But I think in my code these problems are correctly adressed. Info: Windows Explorer uses the API function StrCmpLogicalW() function to do its sorting. There it is called natural sort order. So … Read more

Simple way to sort strings in the (case sensitive) alphabetical order

If you don’t want to add a dependency on Guava (per Michael’s answer) then this comparator is equivalent: private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() { public int compare(String str1, String str2) { int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); if (res == 0) { res = str1.compareTo(str2); } return res; } }; Collections.sort(list, ALPHABETICAL_ORDER); And I … Read more

Comparator with double type

I suggest you use the builtin method Double.compare(). If you need a range for double values to be equal you can use chcek for that first. return Double.compare(p1.getY(), p2.gety()); or if(Math.abs(p1.getY()-p2.getY()) < ERR) return 0; return Double.compare(p1.getY(), p2.gety()); The problem with using < and > is that NaN will return false in both cases resulting … Read more

why does my compare method throw exception — Comparison method violates its general contract!

I suspect the problem occurs when neither value is sponsored. That will return 1 whichever way you call it, i.e. x1.compare(x2) == 1 x2.compare(x1) == 1 That’s invalid. I suggest you change this: object1.getSponsored() && object2.getSponsored() to object1.getSponsored() == object2.getSponsored() in both places. I would probably actually extract this out a method with this signature … Read more

Comparator.comparing(…) of a nested field

You can’t nest method references. You can use lambda expressions instead: return Comparator .comparing(l->l.getCourse().getTeacher().getAge(), Comparator.reverseOrder()) .thenComparing(l->l.getCourse().getStudentSize()); Without the need for reverse order it’s even less verbose: return Comparator .comparing(l->l.getCourse().getTeacher().getAge()) .thenComparing(l->l.getCourse().getStudentSize()); Note: in some cases you need to explicitly state the generic types. For example, the code below won’t work without the <FlightAssignment, LocalDateTime> before comparing(…) … Read more

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn’t follow this principle?

Here’s a simple but realistic example of what can happen if a comparison method is inconsistent with equals. In the JDK, BigDecimal implements Comparable but its comparison method is inconsistent with equals. For example: > BigDecimal z = new BigDecimal(“0.0”) > BigDecimal zz = new BigDecimal(“0.00”) > z.compareTo(zz) 0 > z.equals(zz) false This is because … Read more

Comparable and Comparator contract with regards to null

Comparable doesn’t allow null simply because: a.compareTo(b) == -b.compareTo(a) for all objects a and b where !a.equals(b). More specifically: a.equals(b) ? b.equals(a) && a.compareTo(b) == 0 && b.compareTo(a) == 0 && a.hashCode() == b.hashCode() : !b.equals(a) && a.compareTo(b) != 0 && a.compareTo(b) == -b.compareTo(a) must evaluate to true to satisfy the relevant contracts. So null … Read more