11package com .baeldung .sort ;
22
33import com .baeldung .performance .Employee ;
4+ import com .google .common .collect .Lists ;
5+ import com .google .common .collect .Ordering ;
46
57import java .util .*;
8+ import java .util .stream .Collectors ;
69
710public class SortHashMap {
811
@@ -20,13 +23,36 @@ public static void main(String[] args) {
2023 //treeSetByKey();
2124 //treeSetByValue();
2225
23- sortStream ();
26+ //sortStream();
27+
28+ sortGuava ();
29+ }
30+
31+ private static void sortGuava () {
32+ Ordering <Map .Entry <String , Employee >> orderById = new Ordering <Map .Entry <String , Employee >>() {
33+ @ Override
34+ public int compare (Map .Entry <String , Employee > left , Map .Entry <String , Employee > right ) {
35+ return left .getValue ().getId ().compareTo (right .getValue ().getId ());
36+ }
37+ };
38+
39+ List <Map .Entry <String , Employee >> toList = Lists .newArrayList (map .entrySet ());
40+ Collections .sort (toList , orderById );
41+
42+ toList .forEach (System .out ::println );
2443 }
2544
2645 private static void sortStream () {
2746 map .entrySet ().stream ()
2847 .sorted (Map .Entry .<String , Employee >comparingByKey ().reversed ())
2948 .forEach (System .out ::println );
49+
50+ Map <String , Employee > result = map .entrySet ().stream ()
51+ .sorted (Comparator .comparingLong (e -> e .getValue ().getId ()))
52+ .collect (Collectors .toMap (Map .Entry ::getKey , Map .Entry ::getValue ,
53+ (oldValue , newValue ) -> oldValue , LinkedHashMap ::new ));
54+
55+ result .entrySet ().forEach (System .out ::println );
3056 }
3157
3258 private static void treeSetByValue () {
0 commit comments