Custom thread pool in Java 8 parallel stream

There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one. final int parallelism = 4; ForkJoinPool forkJoinPool = null; try { forkJoinPool = new ForkJoinPool(parallelism); final List<Integer> primes … Read more

Limit a stream by a predicate

Operations takeWhile and dropWhile have been added to JDK 9. Your example code IntStream .iterate(1, n -> n + 1) .takeWhile(n -> n < 10) .forEach(System.out::println); will behave exactly as you expect it to when compiled and run under JDK 9. JDK 9 has been released. It is available for download here: JDK 9 Releases.

Uses for Optional

The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls. This most closely matches use case #1 in the OP’s question. Although, absence of a … Read more

Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

If you have Guava in your project, you can use the Streams.zip method (was added in Guava 21): Returns a stream in which each element is the result of passing the corresponding element of each of streamA and streamB to function. The resulting stream will only be as long as the shorter of the two … Read more

:: (double colon) operator in Java 8

:: is called Method Reference. It is basically a reference to a single method. i.e. it refers to an existing method by name. Short Explanation: Below is an example of a reference to a static method: class Hey { public static double square(double num){ return Math.pow(num, 2); } } Function<Double, Double> square = Hey::square; double … Read more