一、创建stream流
1、通过集合创建,这里以List为例
List<Integer> integerList = new ArrayList<>(); integerList.add(1); integerList.add(2); integerList.add(3); Stream<Integer> stream1 = integerList.stream();
2、Array数组创建
int[] array = {1,2,3}; IntStream stream2 = Arrays.stream(array);
3、通过stream流的of()方法
Stream<Integer> stream3 = Stream.of(1,2,3); stream3.forEach(System.out::println);
4、通过stream流的iterate()方法(无限流,需要limit截断)
Stream<Integer> stream4 = Stream.iterate(1, n -> n + 1).limit(3); stream4.forEach(System.out::println);
5、通过stream流的generate()方法(无限流,需要limit截断)
Stream<Double> stream5 = Stream.generate(Math::random).limit(3); stream5.forEach(System.out::println);
6、文件创建
try { Stream<String> stream6 = Files.lines(Paths.get("data.txt"), Charset.defaultCharset()); stream6.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }