I have a Map that has strings for both keys and values.
Data is like following:
\"question1\", \"1\"
\"question9\", \"1\"
\"que
Provided you cannot use TreeMap
, in Java 8 we can make use of toMap() method in Collectors
which takes following parameters:
Java 8 Example
Map sample = new HashMap<>(); // push some values to map
Map newMapSortedByKey = sample.entrySet().stream()
.sorted(Map.Entry.comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map newMapSortedByValue = sample.entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));
We can modify the example to use custom comparator and to sort based on keys as:
Map newMapSortedByKey = sample.entrySet().stream()
.sorted((e1,e2) -> e1.getKey().compareTo(e2.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2) -> e1, LinkedHashMap::new));