What is difference between Collection.stream().forEach() and Collection.forEach()?

For simple cases such as the one illustrated, they are mostly the same. However, there are a number of subtle differences that might be significant. One issue is with ordering. With Stream.forEach, the order is undefined. It’s unlikely to occur with sequential streams, still, it’s within the specification for Stream.forEach to execute in some arbitrary … Read more

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here. The reason is that the compiler generates a synthetic method holding the trivial body of that … Read more

How can I throw CHECKED exceptions from inside Java 8 streams?

The simple answer to your question is: You can’t, at least not directly. And it’s not your fault. Oracle messed it up. They cling on the concept of checked exceptions, but inconsistently forgot to take care of checked exceptions when designing the functional interfaces, streams, lambda etc. That’s all grist to the mill of experts … Read more

Ignore duplicates when producing map using streams

This is possible using the mergeFunction parameter of Collectors.toMap(keyMapper, valueMapper, mergeFunction): Map<String, String> phoneBook = people.stream() .collect(Collectors.toMap( Person::getName, Person::getAddress, (address1, address2) -> { System.out.println(“duplicate key found!”); return address1; } )); mergeFunction is a function that operates on two values associated with the same key. adress1 corresponds to the first address that was encountered when collecting … Read more

How to sum a list of integers with java streams?

This will work, but the i -> i is doing some automatic unboxing which is why it “feels” strange. mapToInt converts the stream to an IntStream “of primitive int-valued elements”. Either of the following will work and better explain what the compiler is doing under the hood with your original syntax: integers.values().stream().mapToInt(i -> i.intValue()).sum(); integers.values().stream().mapToInt(Integer::intValue).sum();

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

Retrieving a List from a java.util.stream.Stream in Java 8

What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach. [later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)) would be racy if the stream was parallel. Even then, it will … Read more

NullPointerException in Collectors.toMap with null entry values

You can work around this known bug in OpenJDK with this: Map<Integer, Boolean> collect = list.stream() .collect(HashMap::new, (m,v)->m.put(v.getId(), v.getAnswer()), HashMap::putAll); It is not that much pretty, but it works. Result: 1: true 2: true 3: null (this tutorial helped me the most.) EDIT: Unlike Collectors.toMap, this will silently replace values if you have the same … Read more

Is there a concise way to iterate over a stream with indices in Java 8?

The cleanest way is to start from a stream of indices: String[] names = {“Sam”, “Pamela”, “Dave”, “Pascal”, “Erik”}; IntStream.range(0, names.length) .filter(i -> names[i].length() <= i) .mapToObj(i -> names[i]) .collect(Collectors.toList()); The resulting list contains “Erik” only. One alternative which looks more familiar when you are used to for loops would be to maintain an ad … Read more

Convert Iterable to Stream using Java 8 JDK

There’s a much better answer than using spliteratorUnknownSize directly, which is both easier and gets a better result. Iterable has a spliterator() method, so you should just use that to get your spliterator. In the worst case, it’s the same code (the default implementation uses spliteratorUnknownSize), but in the more common case, where your Iterable … Read more

tech