Java 8 – How to sort a Map

Hello Friends

There are two ways to sort  map

1.) By Key

2.) By Value

Here is the example By Key

public static void main(String[] args) {

Map<String, Integer> unsortMap = new HashMap<>();
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(“j”, 50);
unsortMap.put(“m”, 2);
unsortMap.put(“f”, 9);

System.out.println(“Original…”);
System.out.println(unsortMap);

Map<String, Integer> result = new LinkedHashMap<>();

//sort by key, a,b,c…, and put it into the “result” map
unsortMap.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByKey())
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

System.out.println(“Sorted…”);
System.out.println(result);

}

 

 

Here is the example By Value

public static void main(String[] argv) {

Map<String, Integer> unsortMap = new HashMap<>();
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(“j”, 50);
unsortMap.put(“m”, 2);
unsortMap.put(“f”, 9);

System.out.println(“Original…”);
System.out.println(unsortMap);

Map<String, Integer> result = new LinkedHashMap<>();

//sort by value, and reserve, 10,9,8,7,6…
unsortMap.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

System.out.println(“Sorted…”);
System.out.println(result);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s