我知道,一旦集合的流操作为collect/forEach/min/max,,流就关闭了,不再适用于进一步的函数调用。
我的问题是,如何避免“重复流操作”,使我们可以在同一集合上进行不同的流操作,而不需要重复计算?
例如。
public static void main(String[] args) {
List<Integer> ls = new ArrayList<>(Arrays.asList( 11, 9, 7, 11, 24, 13, 37, 16 ));
Stream<Integer> s1 = ls.stream().filter(x -> x > 10).sorted().distinct().limit(4).skip(2);
s1.forEach(System.out::println);
// java.lang.IllegalStateException: stream has already been operated upon or closed
System.out.println(s1.max((x, y) -> x < y ? y : x).get()); // s1 is no longer useable.
}嗯,我知道为了得到s1.max,我必须再次构造Stream,比如:
Stream<Integer> sAnother = ls.stream().filter(x -> x > 10).sorted().distinct().limit(4).skip(2);这是可行的,但似乎第二次做了多余的工作。我希望我们可以使用这个调用序列,并使它只执行一次:
filter(x -> x > 10).sorted().distinct().limit(4).skip(2)然后:(1)执行forEach打印元素。(2)计算最大单元。
不必构造和计算整个流程两次。
有办法做到这一点吗?谢谢。
发布于 2022-07-15 17:52:48
公共静态无效main( 10).distinct().sorted().limit(4).skip(2).toList();args) { List =新ArrayList<>(Arrays.asList( 11,9,7,11,24,13,37,16 ));List s1 = ls.stream().filter(x -> x>ArrayList<>整数max = null;(整数: s1) { if (最大== null integer.compareTo (max ) > 0) { max =整数;}System.out.println(整数);} System.out.println(max);}
发布于 2022-07-15 14:45:12
一个Stream只能消耗一次,而你对它无能为力。但是,您可以做的是收集它,即收集到List (stream.toList()),然后使用该列表进行进一步的执行--在您的示例中,创建两个执行不同工作的新流。
https://stackoverflow.com/questions/72995702
复制相似问题