1
1
import com .google .common .collect .ImmutableSet ;
2
2
import org .junit .Test ;
3
3
4
- import java .util .Arrays ;
5
- import java .util .HashMap ;
6
- import java .util .List ;
7
- import java .util .Map ;
4
+ import java .util .*;
8
5
import java .util .stream .Collectors ;
9
6
10
7
import static org .hamcrest .CoreMatchers .is ;
@@ -49,7 +46,7 @@ public void sortByKeys_reverse() {
49
46
personMap .put (p3 .getId (), p3 );
50
47
51
48
List <Integer > ids = personMap .entrySet ().stream ()
52
- .sorted (Map .Entry .< Integer , Person > comparingByKey (). reversed ( ))
49
+ .sorted (Map .Entry .comparingByKey (( x , y ) -> Integer . compare ( y , x ) ))
53
50
.map (Map .Entry ::getKey )
54
51
.collect (Collectors .toList ());
55
52
@@ -58,11 +55,41 @@ public void sortByKeys_reverse() {
58
55
59
56
@ Test
60
57
public void sortByValues_compareBySetSize () {
61
- new Person (1 , ImmutableSet .of ("A" , "B" , "C" ));
58
+ Person p1 = new Person (1 , ImmutableSet .of ("1" , "2" , "3" ));
59
+ Person p2 = new Person (2 , ImmutableSet .of ("1" , "2" , "3" , "4" ));
60
+ Person p3 = new Person (3 , ImmutableSet .of ("3" ));
61
+
62
+ Map <Integer , Person > personMap = new HashMap <>();
63
+
64
+ personMap .put (p1 .getId (), p1 );
65
+ personMap .put (p2 .getId (), p2 );
66
+ personMap .put (p3 .getId (), p3 );
67
+
68
+ List <Integer > ids = personMap .entrySet ().stream ()
69
+ .sorted (Map .Entry .comparingByValue (Comparator .comparingInt (p -> p .getHobbies ().size ())))
70
+ .map (Map .Entry ::getKey )
71
+ .collect (Collectors .toList ());
72
+
73
+ assertThat (ids , is (Arrays .asList (3 , 1 , 2 )));
62
74
}
63
75
64
76
@ Test
65
77
public void sortByValues_compareBySetSize_reverse () {
66
- new Person (1 , ImmutableSet .of ("A" , "B" , "C" ));
78
+ Person p1 = new Person (1 , ImmutableSet .of ("1" , "2" , "3" ));
79
+ Person p2 = new Person (2 , ImmutableSet .of ("1" , "2" , "3" , "4" ));
80
+ Person p3 = new Person (3 , ImmutableSet .of ("3" ));
81
+
82
+ Map <Integer , Person > personMap = new HashMap <>();
83
+
84
+ personMap .put (p1 .getId (), p1 );
85
+ personMap .put (p2 .getId (), p2 );
86
+ personMap .put (p3 .getId (), p3 );
87
+
88
+ List <Integer > ids = personMap .entrySet ().stream ()
89
+ .sorted (Map .Entry .comparingByValue (Comparator .<Person >comparingInt (p -> p .getHobbies ().size ()).reversed ()))
90
+ .map (Map .Entry ::getKey )
91
+ .collect (Collectors .toList ());
92
+
93
+ assertThat (ids , is (Arrays .asList (2 , 1 , 3 )));
67
94
}
68
95
}
0 commit comments