Java 8 Distinct by property

Consider distinct to be a stateful filter. Here is a function that returns a predicate that maintains state about what it’s seen previously, and that returns whether the given element was seen for the first time: public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); } … Read more

Should I always use a parallel stream when possible?

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if I have a massive amount of items to process (or the processing of each item takes time and is parallelizable) … Read more

Find first element by predicate

No, filter does not scan the whole stream. It’s an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test: List<Integer> list = Arrays.asList(1, 10, 3, 7, 5); int a = list.stream() .peek(num -> System.out.println(“will filter ” + num)) .filter(x … Read more

How to convert a Java 8 Stream to an Array?

The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method. String[] stringArray = stringStream.toArray(String[]::new); What it does is find a method that takes in an integer (the size) as argument, and returns a String[], which is exactly what (one of … Read more

tech