Why Stream.max(Integer::max) compiles?

Consider the following code: Stream<Integer> stream = Stream.of(1,2,3,4); int max = stream.max(Math::max).get(); System.out.println(max);Stream<Integer> stream = Stream.of(1,2,3,4); int max = stream.max(Math::max).get(); System.out.println(max); According to the Javadoc of Steam.max(), the argument for the method max() should be a Comparator. In the code above, the method reference is to static methods of the Math class. But the code … Read more

Java 8 Counter

Before Java 8, developers often think about different ways of writing a counter to count something, e.g., counting word frequency. In Java 8, you can write a counter in two simple lines! In addition you can take advantage of parallel computing. Here is Java 8 counter: package com.programcreek.java8;   import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.Map; … Read more

Retrieve a List from a Stream in Java 8

Method 1 String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" }; Stream<String> stream = Stream.of(arr);String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" }; Stream<String> stream = Stream.of(arr); Method 2 String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" }; Stream<String> stream = Stream.of(arr);   ArrayList<String> list = … Read more

Concat Streams in Java 8

You may often need to concat or merge two streams. In the Stream class, there is a static method concat() that can be used for this purpose. Merge Two Streams String[] arr1 = { "a", "b", "c", "d" }; String[] arr2 = { "e", "f", "g" }; Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); … Read more