|
1 | 1 | package com.craftcoder.java8.stream.map; |
2 | 2 |
|
| 3 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 4 | +import static org.hamcrest.Matchers.contains; |
| 5 | + |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.List; |
| 8 | +import java.util.function.Function; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +import org.junit.Test; |
| 12 | + |
3 | 13 | public class StreamWithMapTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + public void shouldMultiplyEachElementBy2() throws Exception { |
| 17 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); |
| 18 | + |
| 19 | + Function<Integer, Integer> multiplyBy2 = new Function<Integer, Integer>() { |
| 20 | + |
| 21 | + @Override |
| 22 | + public Integer apply(Integer number) { |
| 23 | + return number * 2; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + List<Integer> multipliedNumbers = numbers |
| 28 | + .stream() |
| 29 | + .map(multiplyBy2) |
| 30 | + .collect(Collectors.toList()); |
| 31 | + |
| 32 | + assertThat(multipliedNumbers, contains(2, 4, 6, 8, 10)); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void shouldMultiplyEachElementBy2UsingLambdaExpression() throws Exception { |
| 37 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); |
| 38 | + |
| 39 | + Function<Integer, Integer> multiplyBy2 = number -> number * 2; |
| 40 | + |
| 41 | + List<Integer> multipliedNumbers = numbers |
| 42 | + .stream() |
| 43 | + .map(multiplyBy2) |
| 44 | + .collect(Collectors.toList()); |
| 45 | + |
| 46 | + assertThat(multipliedNumbers, contains(2, 4, 6, 8, 10)); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + public void shouldMultiplyAndTransformIntoStringEachElement() throws Exception { |
| 51 | + List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); |
| 52 | + |
| 53 | + Function<Integer, Integer> multiplyBy2 = number -> number * 2; |
| 54 | + Function<Integer, String> transformIntoString = number -> String.valueOf(number); |
| 55 | + |
| 56 | + List<String> multipliedNumbersAsString = numbers |
| 57 | + .stream() |
| 58 | + .map(multiplyBy2) |
| 59 | + .map(transformIntoString) |
| 60 | + .collect(Collectors.toList()); |
| 61 | + |
| 62 | + assertThat(multipliedNumbersAsString, contains("2", "4", "6", "8", "10")); |
| 63 | + } |
4 | 64 |
|
5 | 65 | } |
0 commit comments