11package org .baeldung .guava ;
22
3+ import static org .hamcrest .Matchers .equalTo ;
34import static org .hamcrest .Matchers .lessThan ;
45import static org .junit .Assert .assertThat ;
6+ import static org .junit .Assert .assertTrue ;
57
68import java .util .Collections ;
79import java .util .List ;
10+ import java .util .Map ;
11+ import java .util .Set ;
812
913import org .junit .Test ;
1014
15+ import com .google .common .base .Function ;
1116import com .google .common .base .Predicate ;
1217import com .google .common .collect .Collections2 ;
18+ import com .google .common .collect .Iterables ;
1319import com .google .common .collect .Lists ;
20+ import com .google .common .collect .Maps ;
21+ import com .google .common .collect .Sets ;
1422
1523public class GuavaFunctionalExamplesTest {
1624
@@ -19,7 +27,7 @@ public class GuavaFunctionalExamplesTest {
1927 // predicates
2028
2129 @ Test
22- public final void whenFilteringStringsAccordingToACondition_thenCorrectResults () {
30+ public final void whenFilteringNumbersAccordingToACondition_thenCorrectResults () {
2331 final List <Integer > randomNumbers = Lists .newArrayList (1 , 2 , 3 , 6 , 8 , 10 , 34 , 57 , 89 );
2432 final Predicate <Integer > acceptEvenNumber = new Predicate <Integer >() {
2533 @ Override
@@ -33,4 +41,38 @@ public final boolean apply(final Integer number) {
3341 assertThat (found , lessThan (0 ));
3442 }
3543
44+ @ Test
45+ public final void givenEvenNumbers_whenCheckingIfAllSatisfyTheEvenPredicate_thenYes () {
46+ final List <Integer > eventNumbers = Lists .newArrayList (2 , 6 , 8 , 10 , 34 , 90 );
47+ final Predicate <Integer > acceptEvenNumber = new Predicate <Integer >() {
48+ @ Override
49+ public final boolean apply (final Integer number ) {
50+ return (number % 2 ) == 0 ;
51+ }
52+ };
53+
54+ assertTrue (Iterables .all (eventNumbers , acceptEvenNumber ));
55+ }
56+
57+ // Set+Function => Map
58+
59+ /**
60+ * - see: http://code.google.com/p/guava-libraries/issues/detail?id=56
61+ */
62+ @ Test
63+ public final void whenMapIsBackedBySetAndFunction_thenCorrect () {
64+ final Function <Integer , Integer > powerOfTwo = new Function <Integer , Integer >() {
65+ @ Override
66+ public final Integer apply (final Integer input ) {
67+ return (int ) Math .pow (input , 2 );
68+ }
69+ };
70+ final Set <Integer > lowNumbers = Sets .newHashSet (2 , 3 , 4 );
71+
72+ final Map <Integer , Integer > numberToPowerOfTwoMuttable = Maps .asMap (lowNumbers , powerOfTwo );
73+ final Map <Integer , Integer > numberToPowerOfTwoImuttable = Maps .toMap (lowNumbers , powerOfTwo );
74+ assertThat (numberToPowerOfTwoMuttable .get (2 ), equalTo (4 ));
75+ assertThat (numberToPowerOfTwoImuttable .get (2 ), equalTo (4 ));
76+ }
77+
3678}
0 commit comments