How to sort Map by key
This example explain how you sort map by key using java8 . Using java 8 we
do following steps
- Convert a Map into a Stream
- Sort it
- Collect and return a new
LinkedHashMap
(keep the order)
example follows same steps coding as which explain below.
package Java8;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortMapByKey {
public static void main(String[] args) {
Map unsortMap = new HashMap<>();
unsortMap.put("z", 10);
unsortMap.put("b", 5);
unsortMap.put("r", 6);
unsortMap.put("a", 20);
unsortMap.put("d", 1);
unsortMap.put("e", 7);
unsortMap.put("y", 8);
unsortMap.put("n", 99);
unsortMap.put("q", 50);
unsortMap.put("m", 2);
unsortMap.put("p", 9);
unsortMap.put("c", 9);
System.out.println("Original...");
System.out.println(unsortMap);
// sort by keys, a,b,c..., and return a new LinkedHashMap
// toMap() will returns HashMap by default, we need LinkedHashMap to keep
the order.
Map result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
// Not Recommend, but it works.
//Alternative way to sort a Map by keys, and put it into the "result" map
Map result2 = new LinkedHashMap<>();
unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
System.out.println("Sorted...");
System.out.println(result);
System.out.println("Sceond way of sorting.");
System.out.println(result2);
}
}
Out put this code is .
Original...
{p=9, a=20, q=50, b=5, r=6, c=9, d=1, e=7, y=8, z=10, m=2, n=99}
Sorted...
{a=20, b=5, c=9, d=1, e=7, m=2, n=99, p=9, q=50, r=6, y=8, z=10}
Sceond way of sorting.
{a=20, b=5, c=9, d=1, e=7, m=2, n=99, p=9, q=50, r=6, y=8, z=10}
How to sort Map by key
Reviewed by Mukesh Jha
on
9:12 AM
Rating:
No comments:
Add your comment