Skip to content
Advertisement

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 relevant for this question.)

The best I have been able to come up with using the Java 8 Streams is the following:

JavaScript

Being unable to construct an Map.Entry due to it being an interface causes the creation of the single entry Map instance and the use of flatMap(), which seems ugly.

Is there a better alternative? It seems nicer to do this using a for loop:

JavaScript

Should I avoid the Stream API for this? Or is there a nicer way I have missed?

Advertisement

Answer

Simply translating the “old for loop way” into streams:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement