File size: 2,757 Bytes
0284885 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package Stream_Case_package;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Case_demo3 {
public static void main(String[] args) {
/*
现在有两个ArrayList集合,分别存储6名男演员的名字和年龄以及6名女演员的名字和年龄。
姓名和年龄中间用逗号隔开。
比如:张三,23
要求完成如下操作:
1、男演员只要名字为3个字的前两人
2、女演员只要姓杨的,并且不要第一个
3、把过滤后的男演员姓名和女演员姓名合并在一起
4、将上一步的演员姓名封装成Actor对象。
5、将所有的演员对象都保存到List集合中
备注:演员类Actor,属性有:name,age
男演员:"蔡坤坤,24","叶鼻咸,23","刘不甜,22","吴签,24","谷嘉,30","肖梁梁,27"
女演员:"赵小茵,35","杨幂,36","高元元,43","张天天,31","刘诗,35","杨小蜜,33"
*/
//1、创建两个ArrayList集合
ArrayList<String> manList = new ArrayList<>();
ArrayList<String> womenList = new ArrayList<>();
//2、添加数据
Collections.addAll(manList, "蔡坤坤,24", "叶鼻咸,23", "刘不甜,22", "吴签,24", "谷嘉,30", "肖梁梁,27");
Collections.addAll(womenList, "赵小茵,35", "杨幂,36", "高元元,43", "张天天,31", "刘诗,35", "杨小蜜,33");
//3、男演员只要名字为3个字的前两人
Stream<String> stream1 = manList.stream()
.filter(s -> s.split(",")[0].length() == 3)
.limit(2);
//4、女演员只要姓杨的,并且不要第一个
Stream<String> stream2 = womenList.stream()
.filter(s -> s.split(",")[0].startsWith("杨"))
.skip(1);
//5、把过滤后的男演员姓名和女演员姓名合并在一起
//演员信息封装成Actor对象
//String -> Actor对象(类型转换)
List<Actor> list = Stream.concat(stream1, stream2).map(new Function<String, Actor>() {
@Override
public Actor apply(String s) {
//"赵小茵,35"
String name = s.split(",")[0];
int age = Integer.parseInt(s.split(",")[1]);
return new Actor(name, age);
}
}).collect(Collectors.toList());
//6、将所有的演员对象都保存到List集合中
System.out.println(list);
}
}
|