java8不但可以提高代码的运行的性能,而且实现起来很优雅,因此学习它是不错的选择。
今天写这篇文章,是因为看到我们部门大佬写的代码,因此将其还原成匿名内部类的时候发现这个retrun是不能省掉的,省去会报错。同时还可以学习到map如果在筛选条件中只有一行的时候,是可以不需要return的,这个是与中间有处理过程是不同的。因此就有了下面的学习:
publicList<CmPatientBasePO>listAll(IntegerfkHospId, IntegerfkTenantId) { CmPatientcmPatient=newCmPatient(); cmPatient.setFkHospId(Objects.isNull(fkHospId) ?UserUtils.getHospId() : fkHospId); cmPatient.setFkTenantId(Objects.isNull(fkTenantId) ?UserUtils.getTenantId() : fkTenantId); List<CmPatient>cmPatientList=cmPatientPOMapper.listByCondition(cmPatient); if (CollectionUtils.isEmpty(cmPatientList)) { returnCollections.emptyList(); } returncmPatientList.stream().filter(Objects::nonNull).map(patient-> { CmPatientBasePOcmPatientBasePO=newCmPatientBasePO(); BeanUtils.copyProperties(patient, cmPatientBasePO); cmPatientBasePO.setAliasInitials(patient.getSpellInitials()); cmPatientBasePO.setPatientName(patient.getAliasName()); returncmPatientBasePO; //需要返回值,此时不可省略 }).collect(Collectors.toList()); }
首先map和peek之间的区别和使用
map是有返回值的,而peek作为中间处理过程,其返回的值是void,这是两者最大的区别,其次官方推荐使用map。而使用peek可以进行中间处理,方便对数据的处理。
/*** @author lyz* @date 2020/5/12 17:03**/publicclassDemo { publicstaticvoidmain(String[] args) { Stream.of("小王:18","小杨:20").map(newFunction<String, People>() { publicPeopleapply(Strings) { String[] str=s.split(":"); Peoplepeople=newPeople(str[0],Integer.valueOf(str[1])); returnpeople; } }).forEach(people->System.out.println("people = "+people)); } }
运行结果:
people=People{name='小王', age=18} people=People{name='小杨', age=20}
修改成map实现:
/**** @description: lambda学习* @author: lyz* @date: 2020/05/12 14:48**/publicclassdemo2 { publicstaticvoidmain(String[] args) { Stream.of("小王:18","小杨:20").map((Strings)->{ String[] str=s.split(":"); Peoplepeople=newPeople(str[0],Integer.valueOf(str[1])); returnpeople; //此处不可省略 }).forEach(people->System.out.println("people = "+people)); } }
运行结果:
people=People{name='小王', age=18} people=People{name='小杨', age=20}
修改成peek实现:
/**** @description: lambda学习* @author: lyz* @date: 2020/05/12 15:16**/publicclassDemo5 { publicstaticvoidmain(String[] args) { Stream.of("小王:18","小杨:20").peek((Strings)->{ String[] str=s.split(":"); Peoplepeople=newPeople(str[0],Integer.valueOf(str[1])); //这里没有return,因此返回的void }).forEach(people->System.out.println("people = "+people)); } }
运行结果:
people=小王:18people=小杨:20
进行数据过滤
/**** @description: stream流学习* @author: lyz* @date: 2020/05/12 15:22**/publicclassDemo6 { publicstaticvoidmain(Stringargs[]){ List<Map<String,Object>>list=newArrayList<>(); for(inti=0;i<5;i++){ Map<String,Object>map=newHashMap<>(); map.put("type",i); list.add(map); } System.out.println("list过滤前的数据:"+list); System.out.println("list过滤前的数量:"+list.size()); //过滤获取 type=2的数据List<Map<String,Object>>list2=list.stream().filter((Mapa) -> ("4".equals(a.get("type").toString()))).collect(Collectors.toList()); //只获取数量也可以这样写Longlist2Count=list.stream().filter((Mapa) -> ("4".equals(a.get("type").toString()))).count(); System.out.println("list过滤后的数据:"+list2); System.out.println("list过滤后的数量:"+list2Count); System.out.println("list过滤后的数量:"+list2.size()); } }
运行结果:
list过滤前的数据:[{type=0}, {type=1}, {type=2}, {type=3}, {type=4}] list过滤前的数量:5 list过滤后的数据:[{type=4}] list过滤后的数量:1 list过滤后的数量:1
进行数据过滤:
/**** @description: lambda学习 使用过滤+循环* @author: lyz* @date: 2020/05/12 15:24**/publicclassDemo7 { publicstaticvoidmain(String[] args) { /* List<String> strArr = Arrays.asList("1", "2", "3", "4");strArr.stream().filter(str ->{return "2".equals(str)?true:false;}).forEach(str ->{System.out.println(str);System.out.println(str+1);});*/List<String>strArr=Arrays.asList("1", "2", "3", "4"); strArr.stream().filter(str->"2".equals(str)?true:false).forEach(str->{ System.out.println(str); System.out.println(str+1); }); } }
运行结果:
2 21
基于扁平流实现:
/**** @description: lambda学习 扁平流使用* @author: lyz* @date: 2020/05/12 16:00**/publicclassDemo12 { publicstaticvoidmain(String[] args) { List<Student>students=newArrayList<>(4); students.add(newStudent("百花", 22, 175)); students.add(newStudent("白条", 40, 178)); students.add(newStudent("略一", 40, 180)); students.add(newStudent("畅享", 50, 185)); List<Student>list=students.stream() .filter(stu->stu.getStature() <180) .collect(Collectors.toList()); System.out.println(list); List<Student>students1=newArrayList<>(); students1.add(newStudent("拉普斯", 22, 175)); students1.add(newStudent("洛夫斯基", 40, 178)); List<Student>studentList=Stream.of(students, students1) .flatMap(stu->stu.stream()).collect(Collectors.toList()); System.out.println(studentList); System.out.println("=============================="); Optional<Student>max=students.stream() .max(Comparator.comparing(stu->stu.getAge())); Optional<Student>min=students.stream() .min(Comparator.comparing(stu->stu.getAge())); //判断是否有值if (max.isPresent()) { System.out.println(max.get()); } if (min.isPresent()) { System.out.println(min.get()); } longcount=students.stream().filter(s1->s1.getAge() <45).count(); System.out.println("年龄小于42岁的人数是:"+count); }
运行结果:
[Student{name='百花', age=22, stature=175}, Student{name='白条', age=40, stature=178}] [Student{name='百花', age=22, stature=175}, Student{name='白条', age=40, stature=178}, Student{name='略一', age=40, stature=180}, Student{name='畅享', age=50, stature=185}, Student{name='拉普斯', age=22, stature=175}, Student{name='洛夫斯基', age=40, stature=178}] ==============================Student{name='畅享', age=50, stature=185} Student{name='百花', age=22, stature=175} 年龄小于42岁的人数是:3
进行字符串拼接
/**** @description: 学习java8,字符串拼接* @author: lyz* @date: 2020/05/12 16:23**/publicclassDemo13 { publicstaticvoidmain(String[] args) { List<Student>students=newArrayList<>(3); students.add(newStudent("绿衣", 22, 175)); students.add(newStudent("红妆", 40, 180)); students.add(newStudent("水月", 50, 185)); Stringnames=students.stream() .map(Student::getName).collect(Collectors.joining(",","[","]")); System.out.println(names); } }
运行结果:
[绿衣,红妆,水月]
进行分组操作
/**** @description: 进行lambda学习,进行分组操作* @author: lyz* @date: 2020/05/12 16:43**/publicclassDemo15 { publicstaticvoidmain(String[] args) { List<User>users=Lists.newArrayList( newUser("高三1班", "stu01", "男"), newUser("高三1班", "stu02", "女"), newUser("高三2班", "stu11", "男"), newUser("高三2班", "stu12", "女"), newUser("高三3班", "stu21", "女"), newUser("高三3班", "stu22", "男"), newUser("高三3班", "stu23", "女")); Map<String, List<User>>collect=users.stream().collect(groupingBy(User::getClassName)); System.out.println(JSON.toJSONString(collect)); System.out.println(); Map<String, Long>collect1=users.stream().collect(groupingBy(User::getClassName, Collectors.counting())); System.out.println(JSON.toJSONString(collect1)); System.out.println(); Map<String, Map<String, User>>collect2=users.stream().collect(groupingBy(User::getClassName, Collectors.toMap(User::getStudentName, o->o))); System.out.println(JSON.toJSONString(collect2)); System.out.println(); } privatestaticclassUser { privateStringclassName; privateStringstudentName; privateStringsex; //省略get/set与构造函数 } }
结果:
{"高三3班":[{"className":"高三3班","sex":"女","studentName":"stu21"},{"className":"高三3班","sex":"男","studentName":"stu22"},{"className":"高三3班","sex":"女","studentName":"stu23"}],"高三2班":[{"className":"高三2班","sex":"男","studentName":"stu11"},{"className":"高三2班","sex":"女","studentName":"stu12"}],"高三1班":[{"className":"高三1班","sex":"男","studentName":"stu01"},{"className":"高三1班","sex":"女","studentName":"stu02"}]} {"高三3班":3,"高三2班":2,"高三1班":2} {"高三3班":{"stu21":{"className":"高三3班","sex":"女","studentName":"stu21"},"stu23":{"className":"高三3班","sex":"女","studentName":"stu23"},"stu22":{"className":"高三3班","sex":"男","studentName":"stu22"}},"高三2班":{"stu12":{"className":"高三2班","sex":"女","studentName":"stu12"},"stu11":{"className":"高三2班","sex":"男","studentName":"stu11"}},"高三1班":{"stu02":{"className":"高三1班","sex":"女","studentName":"stu02"},"stu01":{"className":"高三1班","sex":"男","studentName":"stu01"}}}