Created
July 12, 2015 03:49
-
-
Save bufferings/229c7cd1f004c892a98a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package stream; | |
| import org.hamcrest.CoreMatchers; | |
| import org.junit.Assert; | |
| import org.junit.Test; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.List; | |
| import java.util.function.BinaryOperator; | |
| import java.util.function.Function; | |
| import java.util.function.UnaryOperator; | |
| import java.util.stream.Collector; | |
| import java.util.stream.Collectors; | |
| import java.util.stream.IntStream; | |
| import java.util.stream.Stream; | |
| import static java.util.stream.Collectors.joining; | |
| import static org.hamcrest.CoreMatchers.*; | |
| import static org.junit.Assert.*; | |
| public class ScanCollectorTest { | |
| public <T> List<T> scan(Stream<T> stream, T initialValue, BinaryOperator<T> binaryOperator) { | |
| Collector<T, List<T>, List<T>> collector = Collector.of(() -> { | |
| List<T> list = new ArrayList<>(); | |
| list.add(initialValue); | |
| return list; | |
| }, (list, value) -> { | |
| list.add(binaryOperator.apply(list.get(list.size() - 1), value)); | |
| }, (list1, list2) -> { | |
| list1.addAll(list2); | |
| return list1; | |
| }); | |
| return stream.collect(collector); | |
| } | |
| @Test | |
| public void testScan() { | |
| List<Integer> result = scan( | |
| IntStream.rangeClosed(1, 5).boxed(), | |
| 0, | |
| (n, m) -> n + m); | |
| assertThat(result.toString(), is("[0, 1, 3, 6, 10, 15]")); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment