[英]How to process data in a list using Java Stream
How to iterate over 2 loops in a List using Java Stream. 如何使用Java Stream遍历List中的2个循环。
public class ArrayStreams {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(5);
list.add(7);
list.add(2);
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
System.out.println("i :" + list.get(i) + "J :" + list.get(j));
}
}
}
}
How can i convert this code into Java Stream. 我如何将此代码转换为Java Stream。 Please help!
请帮忙!
How can i convert this code into Java Stream.
我如何将此代码转换为Java Stream。
You should not use Streams for at least two reasons : 您不应出于至少两个原因使用Streams:
println(
). println(
)中使用列表的索引。 Streams are not designed to maintain index of the streamed elements The simplest approach is a 1:1 translation of the loop 最简单的方法是循环的1:1翻译
IntStream.range(0, list.size())
.forEach(i -> IntStream.range(i+1, list.size())
.forEach(j -> System.out.println("i :"+list.get(i)+"J :"+list.get(j))));
You could also use 您也可以使用
IntStream.range(0, list.size())
.forEach(i -> list.subList(i+1, list.size())
.forEach(o -> System.out.println("i :"+list.get(i)+"J :"+o)));
which would be the equivalent of 这相当于
for(int i = 0; i < list.size(); i++) {
for(Integer o: list.subList(i + 1, list.size())) {
System.out.println("i :" + list.get(i) + "J :" + o);
}
}
though it would be better to do 虽然这样做会更好
for(int i = 0; i < list.size(); i++) {
Integer o = list.get(i);
String prefix = "i :" + o + "J :";
for(Integer p: list.subList(i + 1, list.size())) {
System.out.println(prefix + p);
}
}
reducing the redundant work. 减少多余的工作。
A more declarative approach is 更具说明性的方法是
IntStream.range(0, list.size()).boxed()
.flatMap(i -> IntStream.range(i+1, list.size())
.mapToObj(j -> ("i :"+list.get(i)+"J :"+list.get(j))))
.forEach(System.out::println);
Unfortunately, the alternative with the reduced redundant work can't be expressed as Stream operation easily, due to the lack of a simple-to-use pair type. 不幸的是,由于缺少简单易用的配对类型,因此冗余工作量减少的替代方案无法轻松地表示为Stream操作。 One solution would be:
一种解决方案是:
IntStream.range(0, list.size())
.mapToObj(i -> new Object(){ int index=i; String prefix="i :"+list.get(i)+"J :";})
.flatMap( p -> list.subList(p.index+1, list.size()).stream().map(o -> p.prefix+o))
.forEach(System.out::println);
Obviously, that's not more readable than the nested for
loops… 显然,这比嵌套的
for
循环更易读...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.