How to sort an ArrayList of type & lt; Entry & lt; Character, Integer & gt; & Gt;

advertisements

I had a HashMap called map which stored Characters as the key and Integers as the value which I then stored into an ArrayList called entries using the following code:

Set<Entry<Character, Integer>> s = map.entrySet();
ArrayList<Entry<Character, Integer>> entries = new ArrayList<>(s);

Now I am trying to sort these entries based on the Integer value, not the key. I tried to use a lambda expression to implement the Comparator interface, but it is not working. This is my code:

Collections.sort(sortedEntries, (sortedEntries.get(0), sortedEntries.get(1)) -> {
    sortedEntries.get(0).getValue().compareTo(sortedEntries.get(1).getValue())
});

These are the errors I get:

Multiple markers at this line

  • Syntax error, insert ")" to complete Expression

  • The method sort(List, Comparator) in the type Collections is not applicable for the arguments (ArrayList>, Map.Entry, Map.Entry)

  • Syntax error on token "->", ; expected


You could sort the list by the values this way:

list.sort(Comparator.comparing(Entry::getValue));