以下是我的代码:
public static void test1(){
Integer[] arr={1,2,3,4,5,6,7,8,9,9};
Stream<Integer> stream = Arrays.stream(arr);
stream.distinct().filter(integer-> integer>3);
stream.forEach(System.out::println);
}
然后就报错了:
错误出现的原因: Stream API只能被消费一次,后续重复使用已建立的流会报异常!所以stream流是线程安全的!
所以你可以使用以下两种方式:
public static void test1(){
Integer[] arr={1,2,3,4,5,6,7,8,9,9};
Stream<Integer> stream = Arrays.stream(arr);
stream.distinct().filter(integer-> integer>3).forEach(System.out::println);
}
或者:
public static void test1(){
Integer[] arr={1,2,3,4,5,6,7,8,9,9};
Stream<Integer> stream = Arrays.stream(arr);
List<Integer> stream1 =stream.distinct().filter(integer-> integer>3).collect(Collectors.toList());
stream1.forEach(System.out::println);
}
搞定!