Created
April 5, 2018 08:29
-
-
Save rakeshopensource/7985565c6715ea7293297ce86e3725d0 to your computer and use it in GitHub Desktop.
Map Sorting using java8 stream api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rakesh; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class MapDemo { | |
public static void main(String[] args) { | |
Map<String, Integer> unsortMap = new HashMap<String, Integer>(); | |
unsortMap.put("z", 10); | |
unsortMap.put("b", 5); | |
unsortMap.put("a", 6); | |
unsortMap.put("c", 20); | |
unsortMap.put("d", 1); | |
unsortMap.put("e", 7); | |
unsortMap.put("y", 8); | |
unsortMap.put("n", 99); | |
unsortMap.put("g", 50); | |
unsortMap.put("m", 2); | |
unsortMap.put("f", 9); | |
System.out.println("Sort by Key"); | |
unsortMap.entrySet().stream().sorted( | |
Comparator.comparing(Map.Entry::getKey)) | |
.collect(Collectors.toMap(Map.Entry:: getKey, Map.Entry :: getValue, (e1, e2)-> e1, LinkedHashMap:: new)) | |
.forEach((k,v) -> System.out.println("Key : " + k + " Value : " + v)); | |
System.out.println("Sort by Value"); | |
unsortMap.entrySet().stream().sorted( | |
Comparator.comparing(Map.Entry::getValue)) | |
.collect(Collectors.toMap(Map.Entry:: getKey, Map.Entry :: getValue, (e1, e2)-> e1, LinkedHashMap:: new)) | |
.forEach((k,v) -> System.out.println("Key : " + k + " Value : " + v)); | |
System.out.println("Sort by Key Reverse"); | |
unsortMap.entrySet().stream() | |
.sorted(Map.Entry.<String, Integer>comparingByKey().reversed()) | |
.collect(Collectors.toMap(Map.Entry :: getKey , Map.Entry :: getValue, (e1,e2)-> e1 , LinkedHashMap::new)) | |
.forEach((k,v) -> System.out.println("Key : " + k + " Value : " + v)); | |
System.out.println("Sort by Value Reverse"); | |
unsortMap.entrySet().stream() | |
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) | |
.collect(Collectors.toMap(Map.Entry :: getKey , Map.Entry :: getValue, (e1,e2)-> e1 , LinkedHashMap::new)) | |
.forEach((k,v) -> System.out.println("Key : " + k + " Value : " + v)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment