java8学习整理二

简介: java8不但可以提高代码的运行的性能,而且实现起来很优雅,因此学习它是不错的选择。今天写这篇文章,是因为看到我们部门大佬写的代码,因此将其还原成匿名内部类的时候发现这个retrun是不能省掉的,省去会报错。同时还可以学习到map如果在筛选条件中只有一行的时候,是可以不需要return的,这个是与中间有处理过程是不同的。因此就有了

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>() {
@OverridepublicPeopleapply(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"}}}


目录
相关文章
|
9天前
|
消息中间件 前端开发 Java
java学习路径
【4月更文挑战第9天】java学习路径
17 1
|
29天前
|
安全 Java 程序员
学习Java类加载机制
在Java的世界里,每一个类或者接口,在经历编译器后,都会生成一个个.class文件。
18 0
|
1月前
|
Java 关系型数据库 MySQL
37、一篇文章学习 Java 中的日期相关类(Date 和 Calendar),非常常用
37、一篇文章学习 Java 中的日期相关类(Date 和 Calendar),非常常用
27 0
|
2月前
|
Java 数据库连接 开发工具
正式开始JAVA学习之旅
正式开始JAVA学习之旅
39 0
|
2月前
|
存储 Java 编译器
Java 零基础入门学习(小白也能看懂!)
Java 零基础入门学习(小白也能看懂!)
|
2月前
|
SQL 运维 Java
我的互联网学习计划(Java)终身学习计划!
我的互联网学习计划(Java)终身学习计划!
31 1
|
1月前
|
存储 安全 Java
24、使用 Java 官方教程学习:① 类变量和类方法详解;② 深入介绍 main() 方法
24、使用 Java 官方教程学习:① 类变量和类方法详解;② 深入介绍 main() 方法
37 1
|
9天前
|
设计模式 前端开发 安全
Java是一种广泛使用的编程语言,其学习路径可以大致分为以下几个阶段
【4月更文挑战第9天】Java是一种广泛使用的编程语言,其学习路径可以大致分为以下几个阶段
12 1
|
1月前
|
Java 索引
Java中String方法学习总结_kaic
Java中String方法学习总结_kaic
|
5天前
|
Java 存储
键值之道:深入学习Java中强大的HashMap(二)
键值之道:深入学习Java中强大的HashMap
10 0
键值之道:深入学习Java中强大的HashMap(二)