Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream Map<K,V> to List<T>

Given that I have some function that takes two parameters and returns one value , is it possible to convert a Map to a List in a Stream as a non-terminal operation? The nearest I cam find is to use forEach on the map to create instances and add them to a pre-defined List, then start a new Stream from that List. Or did I just miss something?

Eg: The classic "find the 3 most frequently occurring words in some long list of words"

wordList.stream().collect(groupingBy(Function.identity, Collectors.counting))). 

(now I want to stream the entrySetof that map)

sorted((a,b) -> a.getValue().compareTo(b.getValue))).limit(3).forEach(print... 
like image 622
JamesCherrill Avatar asked Jan 20 '14 11:01

JamesCherrill


People also ask

Can we convert map to List in Java?

We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.

Can we use map Stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.


1 Answers

You should get the entrySet of the map and glue the entries to the calls of your binary function:

inputMap.entrySet().stream().map(e->myFun(e.getKey(),e.getValue())); 

The result of the above is a stream of T instances.

Update

Your additional example confirms what was discussed in the comments below: group by and sort are by their nature terminal operations. They must be performed in full to be able to produce even the first element of the output, so involving them as non-terminal operations doesn't buy anything in terms of performance/memory footprint.

It happens that Java 8 defines sorted as a non-terminal operation, however that decision could lead to deceptive code because the operation will block until it has received all upstream elements, and will have to retain them all while receiving.

like image 178
Marko Topolnik Avatar answered Sep 19 '22 17:09

Marko Topolnik