java8学习整理二

2020-07-16 16:01:14 浏览数 (1)

java8不但可以提高代码的运行的性能,而且实现起来很优雅,因此学习它是不错的选择。

今天写这篇文章,是因为看到我们部门大佬写的代码,因此将其还原成匿名内部类的时候发现这个retrun是不能省掉的,省去会报错。同时还可以学习到map如果在筛选条件中只有一行的时候,是可以不需要return的,这个是与中间有处理过程是不同的。因此就有了下面的学习:

代码语言:javascript复制
public List<CmPatientBasePO> listAll(Integer fkHospId, Integer fkTenantId) {
    CmPatient cmPatient = new CmPatient();
    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)) {
        return Collections.emptyList();
    }
    return cmPatientList.stream().filter(Objects::nonNull).map(patient -> {
        CmPatientBasePO cmPatientBasePO = new CmPatientBasePO();
        BeanUtils.copyProperties(patient, cmPatientBasePO);
        cmPatientBasePO.setAliasInitials(patient.getSpellInitials());
        cmPatientBasePO.setPatientName(patient.getAliasName());
        return cmPatientBasePO; //需要返回值,此时不可省略
    }).collect(Collectors.toList());
}

首先map和peek之间的区别和使用

map是有返回值的,而peek作为中间处理过程,其返回的值是void,这是两者最大的区别,其次官方推荐使用map。而使用peek可以进行中间处理,方便对数据的处理。

代码语言:javascript复制
/**
 * @author lyz
 * @date 2020/5/12 17:03
 **/
public class Demo {
    public static void main(String[] args) {
        Stream.of("小王:18","小杨:20").map(new Function<String, People>() {
            @Override
            public People apply(String s) {
                String[] str = s.split(":");
                People people = new People(str[0],Integer.valueOf(str[1]));
                return people;
            }
        }).forEach(people-> System.out.println("people = "   people));
    }
}

运行结果:

代码语言:javascript复制
people = People{name='小王', age=18}
people = People{name='小杨', age=20}

修改成map实现:

代码语言:javascript复制
/**
 *
 * @description: lambda学习
 * @author: lyz
 * @date: 2020/05/12 14:48
 **/
public class demo2 {
    public static void main(String[] args) {
        Stream.of("小王:18","小杨:20").map((String s)->{
            String[] str = s.split(":");
            People people = new People(str[0],Integer.valueOf(str[1]));
            return people; //此处不可省略
        }).forEach(people-> System.out.println("people = "   people));
    }
}

运行结果:

代码语言:javascript复制
people = People{name='小王', age=18}
people = People{name='小杨', age=20}

修改成peek实现:

代码语言:javascript复制
/**
 *
 * @description: lambda学习
 * @author: lyz
 * @date: 2020/05/12 15:16
 **/
public class Demo5 {
    public static void main(String[] args) {
        Stream.of("小王:18","小杨:20").peek((String s)->{
            String[] str = s.split(":");
            People people = new People(str[0],Integer.valueOf(str[1])); //这里没有return,因此返回的void
        }).forEach(people-> System.out.println("people = "   people));

    }
}

运行结果:

代码语言:javascript复制
people = 小王:18
people = 小杨:20

进行数据过滤

代码语言:javascript复制
/**
 *
 * @description: stream流学习
 * @author: lyz
 * @date: 2020/05/12 15:22
 **/
public class Demo6 {
    public static void main(String args[]){
        List<Map<String,Object>> list=new ArrayList<>();
        for(int i=0;i<5;i  ){
            Map<String,Object> map=new HashMap<>();
            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((Map a) -> ("4".equals(a.get("type").toString()))).collect(Collectors.toList());
        //只获取数量也可以这样写
        Long list2Count = list.stream().filter((Map a) -> ("4".equals(a.get("type").toString()))).count();
        System.out.println("list过滤后的数据:" list2);
        System.out.println("list过滤后的数量:" list2Count);
        System.out.println("list过滤后的数量:" list2.size());
    }
}

运行结果:

代码语言:javascript复制
list过滤前的数据:[{type=0}, {type=1}, {type=2}, {type=3}, {type=4}]
list过滤前的数量:5
list过滤后的数据:[{type=4}]
list过滤后的数量:1
list过滤后的数量:1

进行数据过滤:

代码语言:javascript复制
/**
 *
 * @description: lambda学习 使用过滤 循环
 * @author: lyz
 * @date: 2020/05/12 15:24
 **/
public class Demo7 {
    public static void main(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);
        });
    }

}

运行结果:

代码语言:javascript复制
2
21

基于扁平流实现:

代码语言:javascript复制
/**
 *
 * @description: lambda学习 扁平流使用
 * @author: lyz
 * @date: 2020/05/12 16:00
 **/
public class Demo12 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(4);
        students.add(new Student("百花", 22, 175));
        students.add(new Student("白条", 40, 178));
        students.add(new Student("略一", 40, 180));
        students.add(new Student("畅享", 50, 185));

        List<Student> list = students.stream()
                .filter(stu -> stu.getStature() < 180)
                .collect(Collectors.toList());
        System.out.println(list);

        List<Student> students1 = new ArrayList<>();
        students1.add(new Student("拉普斯", 22, 175));
        students1.add(new Student("洛夫斯基", 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());
        }

        long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
        System.out.println("年龄小于42岁的人数是:"   count);
    }

运行结果:

代码语言:javascript复制
[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

进行字符串拼接

代码语言:javascript复制
/**
 *
 * @description: 学习java8,字符串拼接
 * @author: lyz
 * @date: 2020/05/12 16:23
 **/
public class Demo13 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("绿衣", 22, 175));
        students.add(new Student("红妆", 40, 180));
        students.add(new Student("水月", 50, 185));

        String names = students.stream()
                .map(Student::getName).collect(Collectors.joining(",","[","]"));
        System.out.println(names);

    }
}

运行结果:

代码语言:javascript复制
[绿衣,红妆,水月]

进行分组操作

代码语言:javascript复制
/**
 *
 * @description: 进行lambda学习,进行分组操作
 * @author: lyz
 * @date: 2020/05/12 16:43
 **/
public class Demo15 {
    public static void main(String[] args) {
        List<User> users = Lists.newArrayList(
                new User("高三1班", "stu01", "男"),
                new User("高三1班", "stu02", "女"),
                new User("高三2班", "stu11", "男"),
                new User("高三2班", "stu12", "女"),
                new User("高三3班", "stu21", "女"),
                new User("高三3班", "stu22", "男"),
                new User("高三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();
    }


    private static class User {
        private String className;
        private String studentName;
        private String sex;

      //省略get/set与构造函数
    }
}

结果:

代码语言:javascript复制
{"高三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"}}}

0 人点赞