stream()流式操作记录

记录工作中遇到过的流式操作,随用随增:
原始数据:

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
TestPOJO pojo1 = new TestPOJO("China","AA",1, sd.parse("2023-03-28"));
TestPOJO pojo2 = new TestPOJO("China","BB",2, sd.parse("2023-03-27"));
TestPOJO pojo3 = new TestPOJO("America","CC",4, sd.parse("2023-03-26"));
TestPOJO pojo4 = new TestPOJO("Japan","DD",5, sd.parse("2023-03-25"));
    List<TestPOJO> testPOJOList = new ArrayList<>();
    testPOJOList.add(pojo1);
    testPOJOList.add(pojo2);
    testPOJOList.add(pojo3);
    testPOJOList.add(pojo4);

原始输出:
在这里插入图片描述

  1. list转JSON字符串:
// JSONObject用com.alibaba.fastjson.JSONObject;
String s = JSONObject.toJSONString(testPOJOList);

输出:
在这里插入图片描述
2.List中某两个属性分别为key、value,转Map:

Map<String, Integer> collect = testPOJOList.stream().collect(Collectors.toMap(TestPOJO::getName, TestPOJO::getAge));

输出:
在这里插入图片描述
也可写成:

Map<String, Integer> collect = testPOJOList.stream().collect(Collectors.toMap(key -> key.getName(), valueMap -> valueMap.getAge()));

输出:
在这里插入图片描述

3.提取数据构建新的List(Set):

List<User> userList = constructUserInfo(testPOJOList);

/**
  * 构建userList
  * @param testPOJOList
  * @return
  */
public static List<User> constructUserInfo(List<TestPOJO> testPOJOList){
    return testPOJOList.stream().map(testPOJO -> {
        User user = new User();
        user.setName(testPOJO.getName());
        user.setAge(String.valueOf(testPOJO.getAge()));
        return user;
      }).collect(Collectors.toList());
}

输出:
在这里插入图片描述
4.过滤

List<TestPOJO> collect = testPOJOList.stream().filter(testPOJO -> testPOJO.getAge() > 2).collect(Collectors.toList());

输出:
在这里插入图片描述
5.分组

Map<String, List<TestPOJO>> collectMap = testPOJOList.stream().collect(Collectors.groupingBy(TestPOJO::getDept));

输出:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值