Skip to content

Tag: java-stream

Java 8 stream map on entry set

I’m trying to perform a map operation on each entry in a Map object. I need to take a prefix off the key and convert the value from one type to another. My code is taking configuration entries from a Map<String, String> and converting to a Map<String, AttributeType> (AttributeType is just a …

Merge lists with stream API

I have the following situation I have to merge all the lists lst from the ListContainer objects from a Map map. Any idea how, using Java 8 stream API? Answer I think flatMap() is what you’re looking for. For example:

Collect successive pairs from a stream

Given a stream such as { 0, 1, 2, 3, 4 }, how can I most elegantly transform it into given form: { new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4) } (assuming, of course, I’ve defined class Pair)? Edit: This isn’t strictly about ints or primitive streams. The answer should be genera…

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8? Java 8: Java 7: I have lots of for loops that could be “simplified” with lambdas, but is there really any advantage of using them? Would it improve their performance and readability? EDIT I’ll also extend this question to longer methods. I…