-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathStreamWithMapTest.java
More file actions
65 lines (47 loc) · 1.7 KB
/
StreamWithMapTest.java
File metadata and controls
65 lines (47 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package streams;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
public class StreamWithMapTest {
@Test
public void shouldMultiplyEachElementBy2() throws Exception {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Function<Integer, Integer> multiplyBy2 = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer number) {
return number * 2;
}
};
List<Integer> multipliedNumbers = numbers
.stream()
.map(multiplyBy2)
.collect(Collectors.toList());
assertThat(multipliedNumbers, CoreMatchers.hasItems(2, 4, 6, 8, 10));
}
@Test
public void shouldMultiplyEachElementBy2UsingLambdaExpression() throws Exception {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Function<Integer, Integer> multiplyBy2 = number -> number * 2;
List<Integer> multipliedNumbers = numbers
.stream()
.map(multiplyBy2)
.collect(Collectors.toList());
assertThat(multipliedNumbers, CoreMatchers.hasItems(2, 4, 6, 8, 10));
}
@Test
public void shouldMultiplyAndTransformIntoStringEachElement() throws Exception {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Function<Integer, Integer> multiplyBy2 = number -> number * 2;
Function<Integer, String> transformIntoString = number -> String.valueOf(number);
List<String> multipliedNumbersAsString = numbers
.stream()
.map(multiplyBy2)
.map(transformIntoString)
.collect(Collectors.toList());
assertThat(multipliedNumbersAsString, CoreMatchers.hasItems("2", "4", "6", "8", "10"));
}
}