Stream流的使用案例
1. 演员类Actor
public class Actor {private String name;private Integer age;public Actor(String name, Integer age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Actor{" +"name='" + name + '\'' +", age=" + age +'}';}
}
2. 相关案例
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;public class Demo6 {public static void main(String[] args) {/*** 案例一* 定义一个集合, 并添加一些整数: 1,2,3,4,5,6,7,8,9,10* 过滤奇数, 留下偶数, 并把结果保存起来*/ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);List<Integer> newList = list.stream().filter(s -> s % 2 == 0).collect(Collectors.toList());System.out.println(newList);System.out.println("====================");/*** 案例二* 创建一个ArrayList集合, 并添加以下字符串, 字符串前面是姓名, 后面是年龄。 "张三,23","李四,24","王五,25"* 保留年龄大于等于24岁的人, 并将结果保留到map集合中, 姓名为键, 年龄为值*/ArrayList<String> arrayList = new ArrayList<>();Collections.addAll(arrayList,"张三,23","李四,24","王五,25");Map<String, String> map = arrayList.stream().filter(s -> Integer.parseInt(s.split(",")[1]) >= 24).collect(Collectors.toMap(s -> s.split(",")[0], s -> s.split(",")[1]));System.out.println(map);System.out.println("====================");/*** 案例三* 现有两个ArrayList集合, 第一个集合中: 存储六名男演员的名字和年龄, 第二个集合中: 存储六名女演员的名字和年龄* 完成以下操作:* 1. 男演员只要名字为3个字的前两人* 2. 女演员只要姓杨的, 并且不要第一个* 3. 把过滤的男演员姓名和女演员姓名合并在一起* 4. 将上一步的演员信息封装成Actor对象* 5. 将所有的演员对象封装到list集合中* 演员类Actor : 属性 name,age*/ArrayList<String> boyList = new ArrayList<>();ArrayList<String> girlList = new ArrayList<>();Collections.addAll(boyList,"周新驰,56","张大友,62","刘继辉,35","张震,32","萧炎,24","袁天罡,320");Collections.addAll(girlList,"赵小颖,35","杨紫,21","高圆圆,35","张小咪,32","杨玉环,24","杨小小,20");// 男演员只要名字为3个字的前两人List<String> newBoyList = boyList.stream().filter(s -> s.split(",")[0].length() == 3).limit(2).collect(Collectors.toList());// 女演员只要姓杨的, 并且不要第一个List<String> newGirlList = girlList.stream().filter(s -> s.startsWith("杨")).skip(1).collect(Collectors.toList());System.out.println(newBoyList);System.out.println("====================");System.out.println(newGirlList);System.out.println("====================");// 把过滤的男演员姓名和女演员姓名合并在一起List<String> concatList = Stream.concat(newBoyList.stream(), newGirlList.stream()).collect(Collectors.toList());System.out.println(concatList);System.out.println("====================");// 将上一步的演员信息封装成Actor对象,将所有的演员对象封装到list集合中concatList.stream().map(s -> new Actor(s.split(",")[0], Integer.parseInt(s.split(",")[1]))).collect(Collectors.toList()).forEach(s -> System.out.println(s));}
}