java 如何使用java流添加所有内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43625683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:36:10  来源:igfitidea点击:

How to do add all with java streams?

javajava-8java-stream

提问by user3407267

How do I do add all with java 8 ?

如何使用 java 8 添加所有内容?

processeditemList is a Map<Integer, Map<Item, Boolean>> 

As for now I am doing :

至于现在我在做什么:

List<Item> itemList = Lists.newLinkedList();
for (Map<Item, Boolean> entry : processeditemList.values()) {
    itemList.addAll(entry.keySet());
}
return itemList;

回答by Beri

You can use flatMap. It's used to combine multiple streams into a single one. So here you need to create a stream of collections, and then create a stream from each of them:

您可以使用flatMap。它用于将多个流合并为一个流。所以在这里你需要创建一个集合流,然后从它们中的每一个创建一个流:

processeditemList.values().stream()
    .map(Map::keySet)     // Stream<Set<Item>>
    .flatMap(Set::stream) // convert each set to a stream
    .collect(toList());   // convert to list, this will be an ArrayList implmentation by default

If you want to change default List implementation, then you can use below collector:

如果要更改默认列表实现,则可以使用以下收集器:

Collectors.toCollection(LinkedList::new)

LinkedList would be good if you do not know the final size of the list, and you do more insert operations than read.

如果您不知道列表的最终大小,并且您执行的插入操作多于读取操作,则 LinkedList 会很好。

ArrayList is the oposite: more you read, and less add/remove. Because ArrayList under the hood holds an array, which must be rescaled when adding new elements, but never get's reduced, when you remove elements.

ArrayList 正好相反:您阅读的内容越多,添加/删除的内容就越少。因为引擎盖下的 ArrayList 包含一个数组,在添加新元素时必须重新缩放该数组,但在删除元素时永远不会减少。

回答by Jacob G.

I'm on my phone at the moment so I can't promise that this will be syntactically perfect, but here's how you can do it with a Stream:

我现在正在使用手机,所以我不能保证这在语法上是完美的,但是您可以使用以下方法来做到这一点Stream

processeditemList.values().stream()
    .flatMap(e -> e.keySet().stream())
    .collect(Collectors.toCollection(LinkedList::new));

I'm unable to test it currently, but I'll look over the Javadocs and change anything if it's incorrect.

我目前无法测试它,但我会查看 Javadocs 并更改任何不正确的内容。

Edit: I think everything is good. If it doesn't matter which Listimplementation is used, you can change

编辑:我认为一切都很好。如果List使用哪种实现无关紧要,您可以更改

Collectors.toCollection(LinkedList::new)

to

Collectors.toList()