1+ package com .baeldung .guava ;
2+
3+ import com .baeldung .guava .entity .User ;
4+ import com .google .common .base .Functions ;
5+ import com .google .common .base .Joiner ;
6+ import com .google .common .base .Predicate ;
7+ import com .google .common .collect .FluentIterable ;
8+ import org .junit .Assert ;
9+ import org .junit .Test ;
10+
11+ import java .util .ArrayList ;
12+ import java .util .List ;
13+
14+ import static org .hamcrest .CoreMatchers .equalTo ;
15+
16+ public class FluentIterableTest {
17+
18+ private static final int ADULT_AGE = 18 ;
19+
20+ @ Test
21+ public void whenFilteringByAge_shouldFilterOnlyAdultUsers () throws Exception {
22+ List <User > users = new ArrayList <>();
23+ users .add (new User (1L , "John" , 45 ));
24+ users .add (new User (2L , "Michael" , 27 ));
25+ users .add (new User (3L , "Max" , 16 ));
26+ users .add (new User (4L , "Bob" , 10 ));
27+ users .add (new User (5L , "Bill" , 65 ));
28+
29+ Predicate <User > byAge = input -> input .getAge () > ADULT_AGE ;
30+
31+ List <String > results = FluentIterable .from (users )
32+ .filter (byAge )
33+ .transform (Functions .toStringFunction ())
34+ .toList ();
35+
36+ Assert .assertThat (results .size (), equalTo (3 ));
37+ }
38+
39+ @ Test
40+ public void whenCreatingFluentIterableFromArray_shouldContainAllUsers () throws Exception {
41+ User [] usersArray = {new User (1L , "John" , 45 ), new User (2L , "Max" , 15 )};
42+ FluentIterable <User > users = FluentIterable .of (usersArray );
43+
44+ Assert .assertThat (users .size (), equalTo (2 ));
45+ }
46+
47+ @ Test
48+ public void whenAppendingElementsToFluentIterable_shouldContainAllUsers () throws Exception {
49+ User [] usersArray = {new User (1L , "John" , 45 ), new User (2L , "Max" , 15 )};
50+
51+ FluentIterable <User > users = FluentIterable .of (usersArray ).append (
52+ new User (3L , "Bob" , 23 ),
53+ new User (4L , "Bill" , 17 )
54+ );
55+
56+ Assert .assertThat (users .size (), equalTo (4 ));
57+ }
58+
59+ @ Test
60+ public void whenAppendingListToFluentIterable_shouldContainAllUsers () throws Exception {
61+ User [] usersArray = {new User (1L , "John" , 45 ), new User (2L , "Max" , 15 )};
62+
63+ List <User > usersList = new ArrayList <>();
64+ usersList .add (new User (3L , "David" , 32 ));
65+
66+ FluentIterable <User > users = FluentIterable .of (usersArray ).append (usersList );
67+
68+ Assert .assertThat (users .size (), equalTo (3 ));
69+ }
70+
71+ @ Test
72+ public void whenJoiningFluentIterableElements_shouldOutputAllUsers () throws Exception {
73+ User [] usersArray = {new User (1L , "John" , 45 ), new User (2L , "Max" , 15 )};
74+
75+ FluentIterable <User > users = FluentIterable .of (usersArray );
76+
77+ Assert .assertThat (users .join (Joiner .on ("; " )),
78+ equalTo ("User{id=1, name=John, age=45}; User{id=2, name=Max, age=15}" ));
79+ }
80+ }
0 commit comments