[英]Java, Streams: how to convert expression with.collect(Collectors.toList())
How can I convert 我该如何转换
List<Integer> list = new ArrayList<>();
IntStream.range(0, 10).forEach(i -> IntStream.range(0, i + 1).forEach(j -> list.add(Math.max(i, j))));
into a single line expression like 变成单行表达式
List<Integer> list = IntStream.range(0, 10) ... .collect(Collectors.toList());
Use flatMap
: 使用
flatMap
:
IntStream.range(0, 10)
.flatMap(i -> IntStream.range(0, i + 1).map(j -> Math.max(i, j)))
.boxed()
.collect(Collectors.toList());
As a side note, you don't need Math.max
here. 另外,您在这里不需要
Math.max
。 In this case i
is always not less than j
, so the same result can be generated simpler: 在这种情况下,
i
总是不小于j
,因此可以更简单地生成相同的结果:
IntStream.range(0, 10)
.flatMap(i -> IntStream.range(0, i + 1).map(j -> i))
.boxed()
.collect(Collectors.toList());
You can achieve this with flatMap
: 您可以使用
flatMap
实现此目的:
List<Integer> list =
IntStream.range(0,10)
.flatMap(i -> IntStream.range(0, i + 1)
.map(j->Math.max(i,j)))
.boxed()
.collect(Collectors.toList());
EDIT : just tested my code. 编辑:刚刚测试了我的代码。 It seems
mapToObj
doesn't work, so you have to use map
and box the stream later. 似乎
mapToObj
无法正常工作,因此您必须使用map
并在以后将流mapToObj
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.