[Java SDK] [Collection] 一文玩转Java中的Lambda和Stream

简介: [Java SDK] [Collection] 一文玩转Java中的Lambda和Stream

方法 / 步骤

一:基本元素的操作

        List<Integer> sourceList =new ArrayList<>();
        sourceList.add(1);
        sourceList.add(2);
        sourceList.add(3);
        List<Integer> targetList=new ArrayList<>();
        targetList.add(3);
        targetList.add(4);
        targetList.add(5);

        //求与目标List的交集
        List<Integer> noChangeIds = sourceList.stream().filter(source -> targetList.contains(source)).collect(Collectors.toList());
        System.out.println("noChangeIds_"+noChangeIds.toString());
        
        //求与目标List的差集
        List<Integer> waitDelIds = sourceList.stream().filter(source -> !targetList.contains(source)).collect(Collectors.toList());
        System.out.println("waitDelIds" + waitDelIds.toString());
        
        //求与原list的差集
        List<Integer> waitInsert = targetList.stream().filter(target -> !sourceList.contains(target)).collect(Collectors.toList());
        System.out.println("waitInsert" + waitInsert.toString());

二: 对象元素的操作

2.1: List对象中操作

        /**
         * List对象中的交集并集差集
         */
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person(1L,"小明",1,10);
        Person person2 = new Person(2L,"小红",2,11);
        Person person3 = new Person(3L,"小兰",2,10);
        Person person4 = new Person(3L,"小兰",2,10);



        personList.add(person4);
        personList.add(person3);
        personList.add(person2);
        personList.add(person1);
        personList.forEach(temp-> System.out.println(temp.toString()));
        /**
         * 去除重复的对象
         */
        //方法一:
        List<Person> distinctPersonList = removeReObjectById(personList);
        //方法二:
//        List<Person> distinctPersonList = personList.stream().collect(Collectors.collectingAndThen(Collectors
//                                    .toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new));
        distinctPersonList.forEach(temp-> System.out.println("distinctPersonList_"+temp.toString()));
        System.out.println("======================================================");

        /**
         * 找出list中的对象,对应的参数出现了几次
         */
        Map<Long, Long> idRecount = personList.stream().collect(Collectors.groupingBy(person -> person.getId(), Collectors.counting()));
        idRecount.forEach((k,v)-> System.out.println("PersonID : "+k+"在List中出现了"+v+"次"));

        //找出List中重复的对象
        List<Long> reIds = new ArrayList<>();
        idRecount.forEach((k,v)->{if(v > 1){ reIds.add(k);}});
        List<Person> findReObjectById = personList.stream().filter(tempPerson -> reIds.contains(tempPerson.getId()))
                                        .collect(Collectors.collectingAndThen(Collectors
                                        .toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new));
        findReObjectById.forEach(temp-> System.out.println("findReObjectByIdList"+temp.toString()));
    }

    private List<Person> removeReObjectById(List<Person> personList){
        Set<Person> peopleTreeSet = new TreeSet<>(Comparator.comparing(Person::getId));
        peopleTreeSet.addAll(personList);
        return new ArrayList<>(peopleTreeSet);
    }
  • 统计字符串总字符出现的次数
        /**
         * 统计字符串总字符出现的次数
         */
        Map<String, Integer> hashMap = new HashMap<>();
        String inputStr = "ABBCCCDDDDFFFFF";
        List<String> inputStrAsList = Arrays.asList(inputStr.split(""));
        inputStrAsList.forEach(var -> {
            hashMap.merge(var,1,Integer::sum);
        });

        hashMap.forEach((k,v)->{
            System.out.println("key: " + k + " 出现次数: " + v);
        });

2.2: List集合的转换

  • List 换装成Map
   /**
     * 以工号为key,实体内容为value List转换成map
     * 这个注意: 原始List中的实体Key是唯一的,如果不唯一后面的会实体会覆盖前面的
     * @param sourceList
     * @return
     */
    static Map<Long,Staff> list2Map(List<Staff> sourceList){
        //如果有重复Key这么写会报错 Java.lang.IllegalStateException:Duplicate key
        Map<Long, Staff> collect1 = sourceList.stream().collect(Collectors.toMap(Staff::getStaffNo, (var) -> var));
        //这么写如果有重复key后面的会覆盖前面的
        Map<Long, Staff> collect2 = sourceList.stream().collect(Collectors.toMap(Staff::getStaffNo, Function.identity(),(key1, key2) -> key2));
        return collect2;
    }


    static Map<String,List<Staff>> list2MapList(List<Staff> sourceList){
        //按照性别进行分组
        Map<String, List<Staff>> collect = sourceList.stream().collect(Collectors.groupingBy(Staff::getSex));
        //也可以按照工号进行分组
        Map<Long, List<Staff>> collect1 = sourceList.stream().collect(Collectors.groupingBy(Staff::getStaffNo));

        //partitioningBy可以理解为特殊的groupingBy,key值为true和false,当然此时方法中的参数为一个判断语句(用于判断的函数式接口)
        //把List中的元素按条件分区
        Map<Boolean, List<Staff>> collect2 = sourceList.stream().collect(Collectors.partitioningBy(e -> e.getAge() >= 18));
        System.out.println("满18岁的元素有"+ collect2.get(true).toString());
        return collect;
    }

参考资料 & 致谢

【1】Java8特性详解 lambda表达式 Stream
【2】java8新特性5:深入理解Java8 Lambda表达式

目录
相关文章
|
1天前
|
SQL Java 关系型数据库
实时数仓 Hologres产品使用合集之如何安装和使用Java SDK
实时数仓Hologres是阿里云推出的一款高性能、实时分析的数据库服务,专为大数据分析和复杂查询场景设计。使用Hologres,企业能够打破传统数据仓库的延迟瓶颈,实现数据到决策的无缝衔接,加速业务创新和响应速度。以下是Hologres产品的一些典型使用场景合集。
|
3天前
|
Java 开发者
Java中的Lambda表达式:简化你的代码之旅
【8月更文挑战第17天】 在编程的海洋中,简洁是航行的风帆。Lambda表达式,作为Java 8的一大亮点,为开发者提供了一种更为紧凑、易读的编码方式。本篇文章将带你领略Lambda表达式的魅力,从基础概念到实际应用,让你的代码像诗句一样流畅。
13 4
|
3天前
|
Java API 开发者
|
9天前
|
自然语言处理 Java API
"告别Java8 Stream噩梦,JDFrame神器来袭!让你的代码简洁如诗,效率翻倍,编程新体验等你尝鲜!"
【8月更文挑战第11天】Java 8的Stream API以强大的函数式编程能力革新了集合数据处理方式,但其抽象概念和复杂的链式调用让不少开发者望而却步。为此,JDFrame框架应运而生,通过直观易懂的操作符简化Stream使用,减少代码量并提高效率。
25 3
|
8天前
|
并行计算 Java 程序员
探索Java中的Lambda表达式
在Java 8中,引入了Lambda表达式,这一特性极大地简化了代码,提高了开发效率。本文将通过浅显易懂的语言和生动的比喻,带你一步步了解Lambda表达式的魅力所在,从基础语法到实际应用,让你轻松掌握这一强大的工具。
18 1
|
2天前
|
并行计算 Java API
|
4天前
|
前端开发 Oracle Java
Java 22 新增利器: 使用 Java Stream Gather 优雅地处理流中的状态
本文我们分析了 什么 是 “流”,对比了 Java 上几种常见的 “流”库,引入和详细介绍了 Java 22 中的 Stream Gather API 。同时也简单分享了利用 虚拟线程 如何简化 StreammapConcurrent操作符的实现。
|
4天前
|
Oracle Java 关系型数据库
Java10 Lambda 设计和实现问题之在双流 concat 的场景中,确保 s1 和 s2 流水线上的算子与 s3 流水线上的算子正确串联起来,如何实现
Java10 Lambda 设计和实现问题之在双流 concat 的场景中,确保 s1 和 s2 流水线上的算子与 s3 流水线上的算子正确串联起来,如何实现
|
4天前
|
Java API
Java9 Lambda 设计和实现问题之IntStream, LongStream 等类型特定的流接口基于 AbstractPipeline 是如何实现的
Java9 Lambda 设计和实现问题之IntStream, LongStream 等类型特定的流接口基于 AbstractPipeline 是如何实现的
|
4天前
|
Java API
Java8 Lambda 设计和实现问题之在Java 8的Stream API中,parallel=false时collect方法是如何实现的
Java8 Lambda 设计和实现问题之在Java 8的Stream API中,parallel=false时collect方法是如何实现的