Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<String, NavigableMap<Long, Collection<String>>> to List<String> using Java8

Tags:

java

java-8

I am trying to convert Map<String, NavigableMap<Long, Collection<String>>> into List<String> Java 8.

I wrote some code but got stuck some where in mid.

userTopics.values().stream().map(
    new Function<NavigableMap<Long, Collection<String>>, Collection<String>>() {
        @Override
        public Collection<String> apply(NavigableMap<Long, Collection<String>> t) {
            return null;  //TODO
        }
    }
);
like image 411
cody123 Avatar asked Apr 15 '26 02:04

cody123


1 Answers

Just flatMap that s**t:

List<String> values = nestedMap.entrySet()
        .stream()
        .map(Map.Entry::getValue)
        .flatMap(m -> m.entrySet().stream())
        .map(Map.Entry::getValue)
        .flatMap(Collection::stream)
        .collect(toList());

As Holger points out, this is neater:

List<String> values = nestedMap.values()
        .stream()
        .flatMap(m -> m.values().stream())
        .flatMap(Collection::stream)
        .collect(toList());
like image 59
Boris the Spider Avatar answered Apr 17 '26 15:04

Boris the Spider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!