Use the stream example in Java 8 to sort a Map by keys or values. 1. Quick Start
In Java 8, follow this procedure to sort the map. Convert Map to Stream sort it Collect and return a new Linkedhashmap (keep order)
Map result = Map.entryset (). Stream ()
. Sorted (Map.Entry.comparingByKey ())
. Collect (Collectors.tomap ( Map.entry::getkey, Map.entry::getvalue,
(OldValue, NewValue)-> OldValue, linkedhashmap::new));
P.S By default, Collectors.tomap returns a HashMap 2. Sorted by Keys Sortbykeyexample.java
Package com.mkyong.test;
Import Java.util.HashMap;
Import Java.util.LinkedHashMap;
Import Java.util.Map;
Import java.util.stream.Collectors; public class Sortbykeyexample {public static void main (string[] argv) {map<string, integer> Unsortma
p = 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 ("G", 50);
Unsortmap.put ("M", 2);
Unsortmap.put ("F", 9);
System.out.println ("Original ...");
System.out.println (UNSORTMAP); Sort by keys, a,b,c ..., and return a new Linkedhashmap//Tomap () 'll returns HASHMAP by default, we need Link
Edhashmap to keep the order. map<string, integer> 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<string, integer> 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 (RESULT2); }
}
Output
Original ... {a=6, b=5, c=20, d=1, e=7, f=9, g=50, Y=8, z=10, m=2, n=99}
Sorted ... {a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
3. Sort by ValuesSortbyvalueexample.java
package com.mkyong.test;
Package Com.mkyong;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import Java.util.LinkedHashMap;
Import Java.util.Map;
Import java.util.stream.Collectors; public class Sortbyvalueexample {public static void main (string[] argv) {map<string