11import com .google .common .collect .ImmutableSet ;
22import org .junit .Test ;
33
4- import java .util .Arrays ;
5- import java .util .HashMap ;
6- import java .util .List ;
7- import java .util .Map ;
4+ import java .util .*;
85import java .util .stream .Collectors ;
96
107import static org .hamcrest .CoreMatchers .is ;
@@ -49,7 +46,7 @@ public void sortByKeys_reverse() {
4946 personMap .put (p3 .getId (), p3 );
5047
5148 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 ) ))
5350 .map (Map .Entry ::getKey )
5451 .collect (Collectors .toList ());
5552
@@ -58,11 +55,41 @@ public void sortByKeys_reverse() {
5855
5956 @ Test
6057 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 )));
6274 }
6375
6476 @ Test
6577 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 )));
6794 }
6895}
0 commit comments