stream流的三个练习:


Snipaste_2024-02-02_19-40-42.png

ArrayList<Integer>list=new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9,10);


List<Integer> list1 = list.stream()
.filter(s -> s % 2 == 0)
.collect(Collectors.toList());
System.out.println(list1);

[2, 4, 6, 8, 10]



Snipaste_2024-02-02_19-41-29.png

ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "zhangsan,23", "lisi,24", "wangwu,25");

Map<String, Integer> map = list.stream()
.filter(s -> Integer.parseInt(s.split(",")[1]) >= 24)
.collect(Collectors.toMap(
    new Function<String, String>() {
        @Override
        public String apply(String s) {
            return s.split(",")[0];
        }
    }
    ,
    new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            return Integer.parseInt(s.split(",")[1]);
        }
    }

));
System.out.println(map);


//也可以用Lambda简写
/*  Map<String, Integer> map = list.stream().
    filter(s -> Integer.parseInt(s.split(",")[1]) >= 24)
    .collect(Collectors.toMap(s -> s.split(",")[0]
            ,
            s -> Integer.parseInt(s.split(",")[1])
    ));
        System.out.println(map);*/

{lisi=24, wangwu=25}



Snipaste_2024-02-02_19-41-38.png

ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
Collections.addAll(list1, "张老三,23", "李四,24", "王老五,25", "赵老六,26", "钱七,27", "孙老八,28");
Collections.addAll(list2, "杨幂,18", "王祖贤,18", "杨超越,18", "杨紫,18", "宋茜,18", "倪妮,18");

Stream<String> stream1 = list1.stream().filter(s -> s.split(",")[0].length() == 3)
.limit(2);//张老三,23   王老五,25

Stream<String> stream2 = list2.stream().filter( s-> s.split(",")[0].startsWith("杨"))
.skip(1);//杨超越,18   杨紫,18


List<Actor> list = Stream.concat(stream1, stream2)
.map(new Function<String, Actor>() {
    @Override
    public Actor apply(String s) {
        String name = s.split(",")[0];
        int age = Integer.parseInt(s.split(",")[1]);
        Actor a = new Actor(name, age);
        return a;
    }
}).collect(Collectors.toList());

System.out.println(list);


//也可以用Lambda简写
/*Stream.concat(stream1,stream2)
.map(s ->new Actor(s.split(",")[0] , Integer.parseInt(s.split(",")[1])  )  );
*/

[Actor{name = 张老三, age = 23}, Actor{name = 王老五, age = 25}, Actor{name = 杨超越, age = 18},Actor{name = 杨紫, age = 18}]

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成果、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值