[JDK] [Collection] 玩转Java集合之Lambda

🧲 相关资料:

玩转Java集合之常用函数

常用函数

filter()、map()、flatMap()、distinct()、sorted()、peek()、limit()、skip() map(),

  • flatmap 都可以使用 targetList.stream().map(var -> var.getXXX()) 获取相应的参数组成新的list,
  • filter() 也可以同样用匿名占位符进行getXXX()获取, 只是参数 是Predicate<? super T> predicate类型,也就是谓词/断定函数,也就是通过判断返回一个boolean类型的值。
  • flatMap() 作用是一个实体里面包含List类型的元素,进行getXXXlist(),也就是获取这个List元素时候会把常规List<List < xxxxBean > > 这种类型给平铺成 List< xxxxBean> 这种类型。

常用案例

创建测试实体

  • Staff 类
@Data
public class Staff {

    //员工工号
    private Long staffNo;

    //员工工号
    private String staffName;

    //部门编号
    private String departmentNo;

    //部门名称
    private String departmentName;

    //入职日期
    private LocalDateTime joinDatetime;

}

一:基本元素的操作

        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中的Stream
【2】java8新特性5:深入理解Java8 Lambda表达式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OxYGC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值