简体   繁体   English

如何使用java流展平地图值

[英]How to flatten map values using java streams

I am new to Java streams and have a problem at hand. 我是Java流的新手,手头有问题。 I have a map like this: 我有这样的地图:

Map<String, List<String>> specialProductsMap

And i want to flatten the map values to a set which contains all the String values in lists in the specialProductsMap . 我想将映射值展平为一个集合,该集合包含specialProductsMap中列表中的所有String值。 How can i do this using Java Streams? 我如何使用Java Streams执行此操作?

You may use the flatMap operator to get this thing done. 您可以使用flatMap运算符来完成此操作。 Here's how it looks. 这是它的外观。

Set<String> valueSet = specialProductsMap.values().stream()
    .flatMap(List::stream)
    .collect(Collectors.toSet());

First Obtain the list of values from map then use stream api like this 首先从map获取值列表然后像这样使用stream api

Set<String> setOfString = specialProductsMap.values().stream().flatMap(list->list.stream())
            .collect(Collectors.toSet());

Or Like this Using Method reference 或者像这样使用方法参考

Set<String> setOfString = specialProductsMap.values().stream().flatMap(List::stream)
            .collect(Collectors.toSet());

You have to stream your values : 你必须流式传输你的价值观:

Stream<List<String>> myStream = specialProductsMap.values().stream();

Then flatten it : 然后压扁它:

Stream<String> myData = myStream.flatMap(List::stream);

Then collect in a set : 然后收集一组:

Set<String> = myData.collect(Collectors.toSet());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM