简体   繁体   English

Stream.map(...)和Collectors.mapping(...)之间有什么区别?

[英]What's the difference between Stream.map(…) and Collectors.mapping(…)?

I've noticed many functionalities exposed in Stream are apparently duplicated in Collectors , such as Stream.map(Foo::bar) versus Collectors.mapping(Foo::bar, ...) , or Stream.count() versus Collectors.counting() . 我注意到Stream中暴露的许多功能显然都在收集器中重复,例如Stream.map(Foo::bar)Collectors.mapping(Foo::bar, ...)Stream.count()Collectors.counting() What's the difference between these approaches? 这些方法有什么区别? Is there a performance difference? 有性能差异吗? Are they implemented differently in some way that affects how well they can be parallelized? 它们是否以某种方式实现不同,这会影响它们的并行化程度?

The collectors that appear to duplicate functionality in Stream exist so they can be used as downstream collectors for collector combinators like groupingBy() . 似乎在Stream复制功能的收集器存在,因此它们可以用作收集器组合下游收集器 ,例如groupingBy()

As a concrete example, suppose you want to compute "count of transactions by seller". 举一个具体的例子,假设您想要计算“卖家的交易数量”。 You could do: 你可以这样做:

Map<Seller, Long> salesBySeller = 
    txns.stream()
        .collect(groupingBy(Txn::getSeller, counting()));

Without collectors like counting() or mapping() , these kinds of queries would be much more difficult. 如果没有collect counting()mapping()类的收集器,这些类型的查询会更加困难。

There's a big difference. 有很大的不同。 The stream operations could be divided into two group: 流操作可以分为两组:

  • Intermediate operations - Stream.map , Stream.flatMap , Stream.filter . 中间操作 - Stream.mapStream.flatMapStream.filter Those produce instance of the Stream and are always lazy , eg no actual traversal of the Stream elements happens. 那些生成Stream的实例并且总是懒惰的 ,例如,没有实际遍历Stream元素。 Those operations are used to create transformation chain . 这些操作用于创建转换链
  • Terminal operations - Stream.collect , Stream.findFirst , Stream.reduce etc. Those do the actual work, eg perform the transformation chain operations on the stream, producing a terminal value . 终端操作 - Stream.collectStream.findFirstStream.reduce等。执行实际工作,例如对流执行转换链操作,生成终端值 Which could be a List, count of element, first element etc. 可以是List,元素数,第一元素等。

Take a look at the Stream package summary javadoc for more information. 有关更多信息,请查看Stream包摘要 javadoc。

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

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