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 class holding some information. Further explanation is not

What’s the difference between map() and flatMap() methods in Java 8?

In Java 8, what’s the difference between and Stream.flatMap() methods? Answer Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value. This

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 general for a stream

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 know that you can’t return or break the