11package com .baeldung .sort ;
22
3- import com .baeldung .performance .Employee ;
3+ import com .google .common .base .Functions ;
4+ import com .google .common .collect .ImmutableSortedMap ;
45import com .google .common .collect .Lists ;
56import com .google .common .collect .Ordering ;
67
@@ -15,31 +16,24 @@ public static void main(String[] args) {
1516
1617 initialize ();
1718
18- // treeMapSortByKey();
19+ treeMapSortByKey ();
1920
20- // arrayListSortByValue();
21- // arrayListSortByKey();
21+ arrayListSortByValue ();
22+ arrayListSortByKey ();
2223
23- // treeSetByKey();
24- // treeSetByValue();
24+ treeSetByKey ();
25+ treeSetByValue ();
2526
26- // sortStream();
27+ sortStream ();
2728
2829 sortGuava ();
2930 }
3031
3132 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- };
33+ final Ordering <String > naturalReverseValueOrdering =
34+ Ordering .natural ().reverse ().nullsLast ().onResultOf (Functions .forMap (map , null ));
3835
39- List <Map .Entry <String , Employee >> toList = Lists .newArrayList (map .entrySet ());
40- Collections .sort (toList , orderById );
41-
42- toList .forEach (System .out ::println );
36+ System .out .println (ImmutableSortedMap .copyOf (map , naturalReverseValueOrdering ));
4337 }
4438
4539 private static void sortStream () {
@@ -48,17 +42,15 @@ private static void sortStream() {
4842 .forEach (System .out ::println );
4943
5044 Map <String , Employee > result = map .entrySet ().stream ()
51- .sorted (Comparator . comparingLong ( e -> e . getValue (). getId () ))
45+ .sorted (Map . Entry . comparingByValue ( ))
5246 .collect (Collectors .toMap (Map .Entry ::getKey , Map .Entry ::getValue ,
5347 (oldValue , newValue ) -> oldValue , LinkedHashMap ::new ));
5448
5549 result .entrySet ().forEach (System .out ::println );
5650 }
5751
5852 private static void treeSetByValue () {
59- Comparator <Employee > comp = (Employee o1 , Employee o2 ) -> (o1 .getId ().compareTo (o2 .getId ()));
60- SortedSet <Employee > values = new TreeSet <>(comp );
61- values .addAll (map .values ());
53+ SortedSet <Employee > values = new TreeSet <>(map .values ());
6254 System .out .println (values );
6355 }
6456
@@ -81,12 +73,7 @@ private static void treeMapSortByKey() {
8173 private static void arrayListSortByValue () {
8274 List <Employee > employeeById = new ArrayList <>(map .values ());
8375
84- Collections .sort (employeeById , new Comparator <Employee >() {
85-
86- public int compare (Employee o1 , Employee o2 ) {
87- return (int )(o1 .getId () - o2 .getId ());
88- }
89- });
76+ Collections .sort (employeeById );
9077
9178 System .out .println (employeeById );
9279 }
0 commit comments