5.Stream流收集 list和set
/* stream流的收集方法
练习:定义一个集合,并添加一些整数1,2, 3,4, 5,6,7,8,9, 10
将集合中的奇数删除,只保留偶数。
遍历集合得到2,4,6,8,10。*/
public class Test06 {
public static void main(String[] args) {
ArrayList<Integer> list01 = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
list01.add(i);
}
//filter负责过滤数据
//collect负责收集数据,获取流中剩余的
// 数据,但collect不负责创建容器,也不负责把数据添加到容器中
//Collectors.toList()在底层会创建一个List集合,并把所有的数据添加到List集合中
List<Integer> list02 = list01.stream().filter(number -> number % 2 == 0).collect(Collectors.toList());
System.out.println(list02);
Set<Integer> set01 = list01.stream().filter(number -> number % 2 == 0).collect(Collectors.toSet());
System.out.println(set01);
}
}
附练习
public class Test08 {
public static void main(String[] args) {
/*
* Stream流的练习
* 现在有两个ArrayList集合,分别存储6名男演员和6名女演员,要求完成如下的操作
* 男演员只要名字为3个字的前两人
* 女演员只要姓杨的,并且不要第一个
* 把过滤后的男演员姓名和女演员姓名合并到一起
* 把上一步操作后的元素作为构造方法的参数创建演员对象遍历数据
* 演员类Actor,里面有一个成员变量,一个带参构造方法,以及成员变量对应的get/set方法
* */
ArrayList<String> manList = new ArrayList<>();
manList.add("杨过");
manList.add("杨康");
manList.add("郭靖");
manList.add("杨铁心");
manList.add("郭啸天");
manList.add("郭破虏");
ArrayList<String> womanList = new ArrayList<>();
womanList.add("杨夫人");
womanList.add("杨第二夫人");
womanList.add("黄蓉");
womanList.add("包惜弱");
womanList.add("李萍");
womanList.add("阳夫人");
Stream<String> stream1 = manList.stream().filter(name -> name.length() == 3).limit(2);
Stream<String> stream2 = womanList.stream().filter(name -> name.startsWith("杨")).skip(1);
Stream.concat(stream1,stream2).forEach(name->{
Actor actor = new Actor(name);
System.out.println(actor);
});
}
}
class Actor{
private String name;
public Actor() {
}
public Actor(String name) {
this.name = name;
}
@Override
public String toString() {
return "Actor{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

浙公网安备 33010602011771号