Java流式编程

本文介绍了Java流式编程的使用,包括转为List或Set、使用toMap、forEach与Lambda表达式、filter过滤、findFirst方法、sum与mapToLong操作、分组方法如groupingBy,并展示了在不同场景下的应用示例,旨在帮助读者理解和掌握Java流式编程的简洁与高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近刚接触项目,发现项目中大量使用流式编程,这里我分享一下流式的几个基本使用方法,自己以前用的并不多,在这里总结一下

stream() 流式编程 只是一种风格,当然使用流式实现的功能 for 循环也可以实现,但是它的使用对于我们编写的的代码看起来非常简洁,不像循环那样臃肿。

我在这里直接代码演示了:

  • 第一种:转为List或者Set
	String str = "123.456.675.4433.2223";
	List<Integer> collect = Arrays.stream(str.split("\\.")).map(Integer::new).collect(Collectors.toList());
	System.out.println(collect);

在这里插入图片描述

List<ClassInfo> classInfoList = classInfoService.list();
Set<Long> collect = classInfoList.stream().map(ClassInfo::getId).collect(Collectors.toSet());
System.out.println(collect);

在这里插入图片描述

  • 第二种(转为Map应用)
List<ClassInfo> classInfoList = classInfoService.list();
Map<Long, String> classInfoListMap = classInfoList.stream().collect(Collectors.toMap(ClassInfo::getId , ClassInfo::getCourseName));
  • toMap中参数注意(补充)
DemoEntity demoEntity1 = new DemoEntity(3L, 50L, "小明");
DemoEntity demoEntity2 = new DemoEntity(2L, 150L, "小张");
DemoEntity demoEntity3 = new DemoEntity(3L, 250L, "小天");

List<DemoEntity> list = Lists.newArrayList();
list.add(demoEntity1);
list.add(demoEntity2);
list.add(demoEntity3);

// 第一个参数是 key,第二个参数是 value, 第三个参数是  当 Key 冲突时,调用的合并方法
Map<Long, DemoEntity> collect = list.stream().collect(Collectors.toMap(DemoEntity::getId, o -> o, (o1, o2) -> o1));

// 第四个参数,Map 构造器,在需要返回特定的 Map 时使用
// Map<Long, DemoEntity> collect = list.stream().collect(Collectors.toMap(DemoEntity::getId, o -> o, (o1, o2) -> o1, TreeMap::new));

        log.info("result:{}", collect);
  • 第三种:forEach、Lambda
List<ClassInfo> classInfoList = classInfoService.list();
classInfoList.stream().forEach(classInfo -> classInfo.setRemark("123"));
List<String> list = Lists.newArrayList();
classInfoList.stream().forEach(classInfo -> {
     list.add(classInfo.getCourseName());
 });
List<ClassInfo> classInfoList = classInfoService.list();
String collect = classInfoList.stream().map(classInfo -> {
   	String courseName = classInfo.getCourseName();
    return courseName;
}).collect(Collectors.joining(","));
System.out.println(collect);

在这里插入图片描述

List<String> list = Lists.newArrayList();
Stream.of(TestEnum.values()).forEach(value -> {
    list.add(value);
});
  • 第四种:filter的使用(过滤,检出自己需要的数据)
List<ClassInfo> classInfoList = classInfoService.list();
// 把课程名是 软件工程  的 classInfo筛选出来
List<ClassInfo> classInfoStream = classInfoList.stream().filter(classInfo -> {
   	String courseName = classInfo.getCourseName();
   	return "软件工程".equals(courseName);
}).collect(Collectors.toList());
  • 第五种:findFirst()的使用
List<ClassInfo> classInfoList = classInfoService.list();
ClassInfo classInfo = classInfoList.stream().findFirst().get();
System.out.println(JSON.toJSONString(classInfo));
  • sum()、mapToLong()的使用
DemoEntity demoEntity1 = new DemoEntity(4L, 50L, "小明");
DemoEntity demoEntity2 = new DemoEntity(2L, 150L, "小张");
DemoEntity demoEntity3 = new DemoEntity(3L, 250L, "小天");

List<DemoEntity> list = Lists.newArrayList();
list.add(demoEntity1);
list.add(demoEntity2);
list.add(demoEntity3);

// mapToLong、mapToDouble...
long sum = list.stream().filter(o -> o.getNum() != null).mapToLong(DemoEntity::getNum).sum();

log.info("result:{}", sum);

在这里插入图片描述

  • 分组(groupingBy)(为了清晰看到结果,我转成了JSON)
  1. 按照某一属性分组
DemoEntity demoEntity1 = new DemoEntity(4L, 50L, "小明");
DemoEntity demoEntity2 = new DemoEntity(2L, 150L, "小张");
DemoEntity demoEntity3 = new DemoEntity(3L, 250L, "小天");
DemoEntity demoEntity4 = new DemoEntity(1L, 250L, "小飞");
DemoEntity demoEntity5 = new DemoEntity(5L, 250L, "小刚");
DemoEntity demoEntity6 = new DemoEntity(6L, 50L, "小流");

List<DemoEntity> list = Lists.newArrayList();
list.add(demoEntity1);
list.add(demoEntity2);
list.add(demoEntity3);
list.add(demoEntity4);
list.add(demoEntity5);
list.add(demoEntity6);

// 按照类目分组
Map<Long, List<DemoEntity>> collect = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum));

log.info("result:{}", collect);
{
  50: [
    {
      "id": 4,
      "name": "小明",
      "num": 50
    },
    {
      "id": 6,
      "name": "小流",
      "num": 50
    }
  ],
  150: [
    {
      "id": 2,
      "name": "小张",
      "num": 150
    }
  ],
  250: [
    {
      "id": 3,
      "name": "小天",
      "num": 250
    },
    {
      "id": 1,
      "name": "小飞",
      "num": 250
    },
    {
      "id": 5,
      "name": "小刚",
      "num": 250
    }
  ]
}
  1. 指定条件分组
// 按照条件分组
Map<String, List<DemoEntity>> collect1 = list.stream().collect(Collectors.groupingBy(demo -> {
    if (demo.getId() < 3) {
        return "low";
    } else {
        return "high";
    }
}));
{
  "high": [
    {
      "id": 4,
      "name": "小明",
      "num": 50
    },
    {
      "id": 3,
      "name": "小天",
      "num": 250
    },
    {
      "id": 5,
      "name": "小刚",
      "num": 250
    },
    {
      "id": 6,
      "name": "小流",
      "num": 50
    }
  ],
  "low": [
    {
      "id": 2,
      "name": "小张",
      "num": 150
    },
    {
      "id": 1,
      "name": "小飞",
      "num": 250
    }
  ]
}
  1. 拼接属性分组
// 属性拼接分组
Map<String, List<DemoEntity>> collect2 = list.stream().collect(Collectors.groupingBy(demo -> demo.getId() + "_" + demo.getName()));
  1. 复杂分组
Map<Long, Map<String, List<DemoEntity>>> collect3 = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum, Collectors.groupingBy(demo -> {
    if (demo.getId() < 3) {
        return "low";
    } else {
        return "high";
    }
})));
{
  50: {
    "high": [
      {
        "id": 4,
        "name": "小明",
        "num": 50
      },
      {
        "id": 6,
        "name": "小流",
        "num": 50
      }
    ]
  },
  150: {
    "low": [
      {
        "id": 2,
        "name": "小张",
        "num": 150
      }
    ]
  },
  250: {
    "high": [
      {
        "id": 3,
        "name": "小天",
        "num": 250
      },
      {
        "id": 5,
        "name": "小刚",
        "num": 250
      }
    ],
    "low": [
      {
        "id": 1,
        "name": "小飞",
        "num": 250
      }
    ]
  }
}
  1. 求总数
Map<Long, Long> collect4 = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum, Collectors.counting()));
{
  50: 2,
  150: 1,
  250: 3
}
  1. 求和
Map<Long, Long> collect5 = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum, Collectors.summingLong(DemoEntity::getId)));
{
	50: 10,
	150: 2,
	250: 9
}
  1. 分组得最值
Map<Long, DemoEntity> collect6 = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(DemoEntity::getId)), Optional::get)));
{
  50: {
    "id": 6,
    "name": "小流",
    "num": 50
  },
  150: {
    "id": 2,
    "name": "小张",
    "num": 150
  },
  250: {
    "id": 5,
    "name": "小刚",
    "num": 250
  }
}
  1. 分组提取目标信息
Map<Long, Set<String>> collect7 = list.stream().collect(Collectors.groupingBy(DemoEntity::getNum, Collectors.mapping(DemoEntity::getName, Collectors.toSet())));
{
  50: [
    "小明",
    "小流"
  ],
  150: [
    "小张"
  ],
  250: [
    "小刚",
    "小天",
    "小飞"
  ]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值