Skip to main content

Posts

Showing posts from November 13, 2018

Java 8 - Streams - flatMap()

Greetings! With stream API it is easy to iterate over a collection and do whatever operation we like to do. Let's say we have a number list which we would like to print power of 2 of each. List<Integer> attempt1 = Arrays.asList(1, 2, 3, 4, 5); attempt1.stream().map(x -> x * x).forEach(System.out::println); // 1, 4, 9, 16, 25 What if we have a List of List? let's try that out. List<List<Integer>> attempt2 = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(2, 5)); Stream<List<Integer>> attempt2Stream = attempt2.stream(); attempt2Stream.map(x -> x * x).forEach(System.out::println); // compile error attempt2Stream.map(x -> x.stream().map(y -> y * y)).forEach(System.out::println); // java.util.stream.ReferencePipeline$3@4c873330, java.util.stream.ReferencePipeline$3@119d7047 As you can see Stream.map() doesn't give us the expected result for the type Stream<List<Integer>>. This is because map() operation

Java 8 - Streams - reduce()

Greetings! Stream API provides several terminal operations for common tasks like count, min, max, sum and average.  These operations return a single value and do specific task. Stream.collect() operation is also a terminal operations but it return a Collection. reduce() is a more-general purpose operations which can be used to combine the content of stream. These terminal operations are called reduction operations. Stream.reduce() This method mainly has two forms. With initial value. Without initial value. T reduce(T identity, BinaryOperator<T> accumulator); Optional<T> reduce(BinaryOperator<T> accumulator); reduce uses BinaryOperator (which extends BiFunction) functional interface which has the form below. R apply(T t, U u); How Does It Work Let's consider below sum operation. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int result = 0; for (Integer number : numbers) { result = result + number; } Syst