Stream流方法的一些简单练习题
Stream流练习题
1、数据过滤
定义一个集合,并添加一些整数1,2,3,4,5,6,7,8,9,10
过滤奇数,只留下偶数
并将结果保存起来。
/**
* @author 戒爱学Java
* @date 2023/3/23 9:32
*/
public class Test1 {
public static void main(String[] args) {
//1、创建集合
ArrayList<Integer> list = new ArrayList<>();
//2、添加数据
Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);
//3、进行过滤并且进行数据的保存
List<Integer> newList = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
System.out.println(newList);
}
}
2、数据操作
创建一个ArrayList集合,并添加以下字符串,字符串中前面是姓名,后面是年龄
"zhangsan,23"
"lisi,24"
"wangwu,25"
保留年龄大于等于24岁的人,并将结果收集到Map集合中,姓名为键,年龄为值
/**
* @author 戒爱学Java
* @date 2023/3/23 9:38
*/
public class Test2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan,23");
list.add("lisi,24");
list.add("wangwu,25");
Map<String, Integer> newMap = list.stream().filter(s -> 24 <= Integer.parseInt(s.split(",")[1]))
.collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1])));
System.out.println(newMap);
}
}
3、数据操作
现在有两个ArrayList集合,
第一个集合中:存储6名男演员的名字和年龄。第二个集合中:存储6名女演员的名字和年龄。
姓名和年龄中间用逗号隔开。比如:张三,23要求完成如下的操作:
1,男演员只要名字为3个字的前两人2,女演员只要姓杨的,并且不要第一个
3,把过滤后的男演员姓名和女演员姓名合并到一起4,将上一步的演员信息封装成Actor对象。
5,将所有的演员对象都保存到List集合中。
备注:演员类Actor,属性只有一个: name,age
/**
* @author 戒爱学Java
* @date 2023/3/23 9:58
*/
public class Test3 {
public static void main(String[] args) {
/**
* 男演员:"蔡坤坤,24","叶剃咸,23","刘不甜,22","吴签,24","谷嘉,30","肖梁梁,27"
* 女演员:"赵小颖,35","杨颖,36","高元元,43","张天天,31","刘诗,35","杨小幂,33"
*/
ArrayList<String> manList = new ArrayList<>();
ArrayList<String> womenList = new ArrayList<>();
Collections.addAll(manList,"蔡坤坤,24","叶齁咸,23","刘不甜,22","吴签,24","谷嘉,30","肖梁梁,27");
Collections.addAll(womenList,"赵小颖,35","杨颖,36","高元元,43","张天天,31","刘诗,35","杨小幂,33");
Stream<String> stream1 = manList.stream().filter(s -> s.split(",")[0].length() == 3).limit(2);
Stream<String> stream2 = womenList.stream().filter(s -> s.startsWith("杨")).skip(1);
List<Actor> list = Stream.concat(stream1, stream2).map(s -> new Actor(s.split(",")[0], Integer.parseInt(s.split(",")[1])))
.collect(Collectors.toList());
System.out.println(list);
}
}