java8 lambda表达式对集合的处理

試著忘記壹切 提交于 2019-12-23 17:59:13

筛选系列

//从数据库查询出的数据
List<ClassImagePraise> pList = classImagePraiseService.list(lambdaQueryWrapperTow);
//把该集合里面每个对象的name筛选出来
List<String> name= list.stream().map(p -> p.getName()).collect(Collectors.toList());
//把该集合里面每个对象的name筛选出来 筛选的条件是 Id等于 333
List<String> teacherIds = pList.stream().filter(s -> s.getId().equals("333")).map(p -> p.getUserId()).collect(Collectors.toList());
//根据集合的sort属性排序 升序 (简写)
pList .sort(Comparator.comparing(ClassImagePraise::getSort));
//根据集合的sort属性排序 降序  (简写)
pList .sort(Comparator.comparing(ClassImagePraise::getSort).reversed());

排序系列详细

	List<Message> list = getMessageList();
    if (list != null && !list.isEmpty()){
        System.out.println("===排序前如下===");
        list.stream().forEach(item -> System.out.println(item));

        //根据多条件组合排序,先根据msg(升序),再根据id(升序)
        list.sort(Comparator.comparing(Message:: getMsg).thenComparing(Message::getId));

        //根据多条件组合排序,先根据msg(升序),再根据id(降序)
        list.sort(Comparator.comparing(Message:: getMsg).thenComparing(Comparator.comparing(Message::getId).reversed()));

        //根据多条件组合排序,先根据msg(降序),再根据id(降序)
        list.sort(Comparator.comparing(Message:: getMsg).thenComparing(Message::getId).reversed());

        //根据多条件组合排序,先根据msg(降序),再根据id(升序)
        list.sort(Comparator.comparing(Message:: getMsg).reversed().thenComparing(Message::getId));

        System.out.println("===排序后如下===");
        list.stream().forEach(item -> System.out.println(item));

List求和、求最大值、平均值

private static void statisticsList(){
        List<Message> list = getMessageList();
        //求和
        Long sum= list.stream().mapToLong(Message::getId).sum();
        System.out.println("sum = " + sum);

        //求最大值
        Optional<Message> maxMassage = list.stream().collect(Collectors.maxBy(Comparator.comparing(Message::getId)));
        Long maxId = maxMassage.get().getId();
        System.out.println("maxId = " + maxId);


        LongSummaryStatistics lss = list.stream().collect(Collectors.summarizingLong(Message::getId));
        System.out.println("sum = " + lss.getSum());
        System.out.println("max = " + lss.getMax());
        System.out.println("min = " + lss.getMin());
        System.out.println("avg = " + lss.getAverage());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!