Stream流的作用
结合Lambda表达式,简化集合、数组操作
Stream使用步骤
如何获取Stream流对象
常见方法
中间方法:filter、limit、skip、distinct、concat、map
终结方法:forEach、count、collect(可以收集list,set,map)
三个练习题
List<Integer> collect = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.filter(item -> item % 2 == 0)
.collect(Collectors.toList());
ArrayList<String> strings = new ArrayList<>();
Collections.addAll(strings, "zhangsan, 23", "lisi, 24", "wangwu, 25");
Map<String, String> collect1 = strings.stream().filter(s -> Integer.parseInt(s.split(",")[1].trim()) >= 24)
.collect(Collectors.toMap(
item -> item.split(",")[0],
item -> item.split(",")[1]
));
System.out.println(collect1);
class Actor{
String name;
Integer age;
public Actor(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Actor{" +
"name='" + name + '\\'' +
", age=" + age +
'}';
}
}
ArrayList<String> actors1 = new ArrayList<>();
actors1.add("张三三,23");
actors1.add("李四四,32");
actors1.add("王五五,27");
actors1.add("赵佳,29");
actors1.add("孙丽,31");
actors1.add("孙丽丽,31");
ArrayList<String> actors2 = new ArrayList<>();
actors2.add("杨琪,26");
actors2.add("杨萌,28");
actors2.add("林一,25");
actors2.add("王勇,33");
actors2.add("陈丹,30");
actors2.add("杨洋,24");
Stream<String> s1 = actors1.stream().filter(s -> s.split(",")[0].length() == 3)
.limit(2);
Stream<String> s2 = actors2.stream().filter(s -> s.startsWith("杨"))
.skip(1);
List<Actor> collect = Stream.concat(s1, s2).map((item) -> {
String name = item.split(",")[0];
String age = item.split(",")[1];
return new Actor(name, Integer.parseInt(age));
}).collect(Collectors.toList());
System.out.println(collect);