Java Stream converter Map<String, Obj> to List<Obj>

Asked

Viewed 212 times

0

I have this object filled:

    Map<String, List<LogLine>> logMap = new TreeMap<>();

And after I’ve made a filter, I’d like a flat list of it, but I can only create a list

List<List<LogLine>>  foo = logMap.entrySet().stream()
            .filter(map -> map.getValue().size() > parameters.getThreshold())
            .map(map -> map.getValue())
            .collect(Collectors.toList());  

How can I create only one List with all Logline using stream? I tried to use flatMap, but the compiler won’t let me.

  • So I know problem is turning from Map<K, List<V>> for List<V>?

1 answer

1


I believe the operator you want is the flatMap:

List<LogLine> foo = logMap.entrySet().stream()
                .filter(map -> map.getValue().size() > parameters.getThreshold())
                .flatMap(map -> map.getValue().stream())
                .collect(Collectors.toList());

It subistitui the current stream [logMap.entrySet().stream()] by a new stream produced by applying a mapping function to each element [map.getValue().stream()].

  • Exactly, I did exactly the same thing a little bit later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.