java8 lambda表达式对集合的处理

筛选系列

//从数据库查询出的数据
List pList = classImagePraiseService.list(lambdaQueryWrapperTow);
//把该集合里面每个对象的name筛选出来
List name= list.stream().map(p -> p.getName()).collect(Collectors.toList());
//把该集合里面每个对象的name筛选出来 筛选的条件是 Id等于 333
List 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 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 list = getMessageList();
        //求和
        Long sum= list.stream().mapToLong(Message::getId).sum();
        System.out.println("sum = " + sum);

        //求最大值
        Optional 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());
}

你可能感兴趣的:(java,lambda,stream,lambda,stream,java)