Stream

2023/5/31

# Stream 流

# 1 过滤之后放到List集合中

ArrayList<String> list1 = new ArrayList();
Collections.addAll(list1, "蔡小小,29", "叶良辰,23", "刘不一,123", "吴妹,23", "谷哥,30", "肖肖,26");
        //获取所有年龄大于24岁所有的人名
        List<String> names = new ArrayList<>();
        list1.stream()
                .filter(s -> Integer.parseInt(s.split(",")[1])>24)
                .map(s -> s.split(",")[0])
                .forEach(names::add);
        System.out.println("names = " + names);

# 2 过滤之后放到Map

List<HashMap<String, Integer>> collect2 = list2.stream()
        .filter(s -> Integer.parseInt(s.split(",")[1]) >= 25)
        .map(s -> {
            HashMap<String, Integer> hashMap = new HashMap();
            hashMap.put(s.split(",")[0].toString(), Integer.parseInt(s.split(",")[1]));
            return hashMap;
        }).collect(Collectors.toList());

# 4 流合并

Stream<String> concat = Stream.concat(stream1, stream2);

# 5过滤放到实体类

# 5.1 原始写法
Stream<Actor> actorStream = concat.map(
        new Function<String, Actor>() {
            @Override
            public Actor apply(String s) {
                return new Actor(s.split(",")[0],Integer.parseInt(s.split(",")[1]));
            }
        }
);
# 5.2 简写
Stream<Actor> actorStream = concat.map(s -> new Actor(s.split(",")[0], Integer.parseInt(s.split(",")[1])));
final List<Actor> collect = actorStream.collect(Collectors.toList());