How to use Java Comparator to sort by last character in string?

user22261 :

Say I have an inventory map :

Map<String, Integer> inventory = new TreeMap<>()

and I want to sort inventory by the last character in the String, how would I do this with a Comparator? How would I handle errors if it's an empty string?

pero_hero :

you can define a simple comparator:

 Comparator<String> comp = Comparator.comparing(s -> s.length() > 0 ? s.substring(s.length()-1) : "");

then you can instantiate a treemap with that comparator:

 Map<String, Integer> map = new TreeMap<>(comp);
    map.put("xxxa", 11);
    map.put("pppb", 2);
    map.put("lllc", 3);
    map.put("iiid", 3);

to get this output:

{xxxa=11, pppb=2, lllc=3, iiid=3}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=343578&siteId=1