package com.fgy.demo; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Stream; /** * 使用stream流的方式,遍历集合,对集合中的数据进行过滤 */ public class Demo01Stream { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("张无忌"); list.add("周芷若"); list.add("赵敏"); list.add("张三丰"); list.add("张三"); // 把集合(只能是单列集合)转换成Stream流 list.stream() .filter(name -> name.startsWith("张")) .filter(name -> name.length() == 3) .forEach(name -> System.out.println(name)); // 张无忌 // 张三丰 // 把数组转换成Stream流 // Integer[] arr = {1, 2, 3, 4, 5}; // Stream<Integer> stream1 = Stream.of(arr); Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5); stream2.forEach(num -> System.out.print(num + " ")); System.out.println(); // 将流中的元素映射到另一个流中,可以使用map方法 Stream<Integer> stream3 = Stream.of("10", "20", "30", "40", "50").map(s -> Integer.parseInt(s)); stream3.forEach(i -> System.out.print(i + " ")); System.out.println(); // 统计stream流中元素的个数 ArrayList<Integer> list1 = new ArrayList<>(); list1.add(1); list1.add(2); list1.add(3); long count = list1.stream().count(); System.out.println(count); // limit方法用于截取流中的元素,只取用前几个 Stream.of("哈哈", "嘿嘿", "嘻嘻", "呵呵", "憨憨").limit(3).forEach(s -> System.out.println(s)); System.out.println("------------------"); // skit方法跳过前几个元素 Stream.of("哈哈", "嘿嘿", "嘻嘻", "呵呵", "憨憨").skip(3).forEach(s -> System.out.println(s)); System.out.println("------------------"); // concat方法合并两个流 Stream<Integer> stream4 = Stream.of(1, 2, 3); Stream<Integer> stream5 = Stream.of(4, 5, 6); Stream<Integer> concat = Stream.concat(stream4, stream5); concat.forEach(i -> System.out.print(i + " ")); } }