The collectors that appear to duplicate functionality in Stream
exist so they can be used as downstream collectors for collector combinators like 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…