最近刚接触项目,发现项目中大量使用流式编程,这里我分享一下流式的几个基本使用方法,自己以前用的并不多,在这里总结一下
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();