Answers for "hashmap sort by value java 8"

1

sorting hashmap by key in java 8

Map<String, String> 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));
Posted by: Guest on May-20-2021
0

sort a map based on keys and values using java 8

Map< Integer, String> map=new HashMap<Integer, String>();

map.put(101, "Hemendra");
map.put(99, "Andrew");
map.put(103, "Anish");
map.put(18, "Mohan");
map.put(11, "Christine");
map.put(109, "Rebeca");
map.put(111, "David");
map.put(19, "Rahim");
map.put(10, "Krishna");

Required to sort the map:

1. On the basis of keys:

[10=Krishna, 11=Christine, 18=Mohan, 19=Rahim, 99=Andrew, 101=Hemendra, 103=Anish, 109=Rebeca, 111=David]

2. On the basis of values:

[99=Andrew, 103=Anish, 11=Christine, 111=David, 101=Hemendra, 10=Krishna, 18=Mohan, 19=Rahim, 109=Rebeca]

Solution:

System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList()));
System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList()));
Posted by: Guest on July-02-2020

Code answers related to "hashmap sort by value java 8"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language