为什么 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())
"部分没有捷径/方便的方法?在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)、joining()、groupingBy() 等快捷方法.
Also toSet(), toCollection(Supplier), joining(), groupingBy() and other shortcut methods are available there.
这篇关于为什么 Stream 没有 toList() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!