单列集合
ArrayList<Integer> list = new ArrayList<Integer>(List.of(1, 2, 3, 4,4,4)); //filter负责过滤数据 //collect负责收集数据 //获取流中剩余的数据,但是他不负责创建容器,也不负责把数据添加到容器中 //Collectors.toList()会在底层创建一个List集合,并把所以的数据添加到List集合中。 List<Integer> list1 = list.stream().filter(number -> number % 2 == 0).collect(Collectors.toList()); System.out.println(list1); Set<Integer> set = list.stream().filter(number -> number % 2 == 0).collect(Collectors.toSet()); System.out.println(set); //[2, 4, 4, 4] //[2, 4]双列集合
public static void main(String[] args) { /** * Steam流的收集方法 * * 创建一个ArrayList集合,并添加以下的字符串,字符串中前面是姓名,后面是年龄 * "zhangsan,23" * "lisi,24" * "wangwu,25" * 保留年龄大于等于24岁的人,并将结果收集到Map集合中,姓名为键,年龄为值 */ ArrayList<String> list = new ArrayList<>(List.of("zhangsan,23","lisi,24","wangwu,25")); Map<String,Integer> map = list.stream().filter((String s)->{ String[] split = s.split(","); int i = Integer.parseInt(split[1]); return i>=24; }).collect(Collectors.toMap( (String s)-> { return s.split(",")[0]; }, (String s)->{ return Integer.valueOf(s.split(",")[1]); } )); map.forEach((String s,Integer i)->{ System.out.println(s+"---"+i); }); } Stream流综合练习【应用】案例需求
代码实现
演员类
public class Actor { private String name; public Actor(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }测试类
package com.cnblogs.gonghr; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class test13 { public static void main(String[] args) { String actor_man_one = "周润发"; String actor_man_two = "成龙"; String actor_man_three = "刘德华"; String actor_man_four = "吴京"; String actor_man_five = "周星驰"; String actor_man_six = "李连杰"; ArrayList<String> actors_man = new ArrayList<>(List.of(actor_man_one, actor_man_two, actor_man_three, actor_man_four, actor_man_five, actor_man_six)); String actor_woman_one = "林心如"; String actor_woman_two = "张曼玉"; String actor_woman_three = "杨超越"; String actor_woman_four = "林志玲"; String actor_woman_five = "周冬雨"; String actor_woman_six = "杨颖"; ArrayList<String> actors_woman = new ArrayList<>(List.of(actor_woman_one, actor_woman_two, actor_woman_three, actor_woman_four, actor_woman_five, actor_woman_six)); Stream<String> actorStream_man= actors_man.stream().filter(actor -> actor.length() == 3).limit(2); Stream<String> actorStream_woman = actors_woman.stream().filter(actor -> actor.startsWith("杨")).skip(1); Stream.concat(actorStream_man, actorStream_woman).forEach(s->{ Actor actor = new Actor(s); System.out.println(actor); }); } } //Actor{name='周润发'} //Actor{name='刘德华'} //Actor{name='杨颖'}