为什么Stream没有toList()方法? [英] Why didn't Stream have a toList() method?
问题描述
使用Java 8流时,采用列表,从中创建流,执行业务并将其转换回来是很常见的。类似于:
When using the Java 8 streams, it's quite common to take a list, create a stream from it, do the business and convert it back. Something like:
Stream.of(-2,1,2,-5)
.filter(n -> n > 0)
.map(n -> n * n)
.collect(Collectors.toList());
为什么' .collect没有捷径/方便的方法(Collectors.toList())
'part?在Stream接口上,有将结果转换为数组的方法,名为 toArray()
,为什么 toList()
是缺少?
Why there is no short-cut/convenient method for the '.collect(Collectors.toList())
' part? On Stream interface, there is method for converting the results to array called toArray()
, why the toList()
is missing?
恕我直言,将结果转换为列表比数组更常见。我可以忍受这种说法,但称这种丑陋是令人讨厌的。
IMHO, converting the result to list is more common than to array. I can live with that, but it is quite annoying to call this ugliness.
任何想法?
推荐答案
最近我写了一个名为 StreamEx 的小型库,它扩展了Java流并在许多方面提供了这种方法。其他功能:
Recently I wrote a small library called StreamEx which extends Java streams and provides this exact method among many other features:
StreamEx.of(-2,1,2,-5)
.filter(n -> n > 0)
.map(n -> n * n)
.toList();
还有toSet(),toCollection(Supplier),join(),groupingBy()和其他快捷方法那里有。
Also toSet(), toCollection(Supplier), joining(), groupingBy() and other shortcut methods are available there.
这篇关于为什么Stream没有toList()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!