stream ➡ 中间方法 ➡ 终结方法
ArrayList<String> list = new ArrayList<>();
list.stream()...;
HashMap<String,Integer> hm = new HashMap<>();
hm.keySet().stream().forEach(s->System.out.println(s)); // 键
hm.entrySet().stream().forEach(s->System.out.println(s)); // 键值对
int[]arr={1,2,3,4,5};
Arrays.stream(arr).forEach(s->System.out.println(s));
Stream.of(1,2,3,4,5,6,7,8).forEach(s->system.out.printIn(s));
过滤数据 startsWith(),以什么开头
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().filter(f->f.startsWith("x")).forEach(System.out::println); // xl xxl
截取前面的数据
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().limit(1).forEach(System.out::println); // lx
截取后面的数据
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().skip(1).forEach(System.out::println); // xl xxl
合并两个流成为一个流
ArrayList<String> list1 = new ArrayList<>(List.of("lx","xl","xxl"));
ArrayList<String> list2 = new ArrayList<>(List.of("lx","xl","xxl"));
Stream.concat(list1,list2).forEach(System.out::println);
去重,依赖hashCode和equals方法
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().distinct().forEach(System.out::println);
终结方法和收集方法只能有一个。不可以同时存在
对每个元素进行操作
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().forEach(System.out::println); // lx xl xxl
返回的是流中的元素的个数
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().count(); // 3
stream流是不可以直接修改源数据的,需要用到其他的方法
收集最后的结果,只管收集,不管其他
ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().filter(f->f.startsWith("x")).collect(); // xl xxl
收集之后需要用方法来创建容器,方法都有返回值
创建一个List容器
List<String> l = list.stream().filter(f->f.startsWith("x")).collect(Collectors.ToList()); // xl xxl
List<String> l = list.stream().filter(f->f.startsWith("x")).toList();
创建一个Set容器
创建一个Map容器
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan,23");
list.add("lisi,24");
list.add("wangwu,25");
Map<String,Integer> map = list.stream().collect(Collectors.toMap(
m -> m.split(",")[0],
m -> Integer.parseInt(m.split(",")[1]),
))