Bootstrap

使用stream对LIst实现过滤、排序、分组、求和、平均

Grade(班级)

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Grade implements Serializable {
    /**
     * 学号
     */
    private String stuNo;
    /**
     * 学生名字
     */
    private String stuName;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 学生班级
     */
    private String stuClass;
    /**
     * 语文成绩
     */
    private Double chineseScore;
    /**
     * 数学成绩
     */
    private Double mathScore;
    /**
     * 英语成绩
     */
    private Double englishScore;
     /**
     * 薪资待遇
     */
    private BigDecimal salary;
}

测试类

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class StremDemoList {
    public static void main(String[] args) {
        Grade liuBeiGrade = new Grade("20220001", "刘备", 38, "101", 98.0, 99.70, 77.50, new BigDecimal(5900));
        Grade guanYuGrade = new Grade("20220002", "关羽",35, "101", 95.0, 89.70, 97.50, new BigDecimal(7900));
        Grade zhangFeiGrade = new Grade("20220003", "张飞", 23, "101", 97.0, 89.70, 97.50, new BigDecimal(6700));
        Grade lvBuGrade = new Grade("20220004", "吕布",24, "102", 78.0, 79.70, 97.50, new BigDecimal(5800));
        Grade zhaoYunGrade = new Grade("20220005", "赵云", 25, "102", 94.0, 89.70, 87.50, new BigDecimal(10000));
        Grade caoCaoGrade = new Grade("20220006", "曹操", 21, "105", 78.0, 89.70, 97.50, new BigDecimal(3700));
        Grade caoCaoGrade2= new Grade("20220006", "曹操2", 27, "105", 78.0, 89.70, 97.50, new BigDecimal(2300));


        List<Grade> gradeList = Arrays.asList(liuBeiGrade, guanYuGrade, zhangFeiGrade, lvBuGrade, zhaoYunGrade,caoCaoGrade);
    }
}

1. 过滤

        // 过滤语文成绩>90
        List<Grade> objectList = gradeList.stream()
                .filter(Objects::nonNull)
                .filter(grade -> grade.getChineseScore() > 90).collect(Collectors.toList());
        log.info("objectList:{}", JSON.toJSONString(objectList));
        
        // 班级为 101的学生
        List<Grade> grades = gradeList.stream().filter(Objects::nonNull).filter(grade -> grade.getStuClass().equals("101")).collect(Collectors.toList());
        log.info("grades:{}", JSON.toJSONString(grades));

2. 排序

        // 按照语文成绩排序
        List<Grade> gradeList1 = gradeList.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparingDouble(Grade::getChineseScore)).collect(Collectors.toList());
        log.info("gradeList1:{}", JSON.toJSONString(gradeList1));

3. 分组

        // 按照班级分组
        Map<String, List<Grade>> stringListMap = gradeList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(Grade::getStuClass));
        log.info("stringListMap:{}", JSON.toJSONString(stringListMap));

4. 求和

        //求和
//        //基本类型
        int sumAge = gradeList.stream().mapToInt(Grade::getAge).sum();
        log.info("sumAge:{}", sumAge);
        // Double、mapToLong()、mapToDouble()、mapToInt()
        Double sumMathScore = gradeList.stream().mapToDouble(Grade::getMathScore).sum();
        log.info("sumMathScore:{}", sumMathScore);
//        //BigDecimal求和
        BigDecimal totalQuantity = gradeList.stream().map(Grade::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add);
        log.info("totalQuantity:{}", totalQuantity);

5. 平均值

        // 求语文成绩的平均分(方式1)
        double adv1 = gradeList.stream().filter(Objects::nonNull).mapToDouble(Grade::getChineseScore).average().orElseThrow(IllegalStateException::new);
        log.info("adv1:{}", adv1);

        // 求语文成绩的平均分(方式1)
        double sum = gradeList.stream().filter(Objects::nonNull).mapToDouble(Grade::getChineseScore).sum();
        double adv2 = sum / (double) gradeList.size();
        log.info("adv2:{}", adv2);

6. List转换为map

        // List 转换为Map
        // Map<学生名字, 学号>
        Map<String, String> map = gradeList.stream().collect(Collectors.toMap(Grade::getStuName, Grade::getStuNo));
        log.info("map:{}", JSON.toJSONString(map));

        // 需要注意的是:
        // toMap 如果集合对象有重复的key,会报错Duplicate key ....
        // grade1,grade2的stuNo都为xx。可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
       // Map<String,Grade>
        Map<String, Grade> gradeMap = gradeList.stream().collect(Collectors.toMap(Grade::getStuNo, a -> a, (k1, k2) -> k1));
        log.info("gradeMap:{}", JSON.toJSONString(gradeMap));

7. 获取list某个字段组装新list

      List<String> stuNoList = gradeList.stream().map(g -> g.getStuNo()).collect(Collectors.toList());
        log.info("stuNoList:{}", JSON.toJSONString(stuNoList));

8. 批量设置list列表字段为同一个值

        gradeList.stream().forEach(a->{
            a.setStuClass("s001");
        });
        log.info("gradeList:{}", JSON.toJSONString(gradeList));

9. 判断对象、字段为空

        // 判断对象为空
        gradeList.stream().filter(x-> x!= null);
        gradeList.stream().filter(Objects::nonNull);

        // 判断字段为空
        gradeList.stream().filter(g -> g.getChineseScore()!=null);

10. 去重

10.1 distinct方法进行去重
        // 去重
        List<Long> idList = new ArrayList<Long>();
        idList.add(1L);
        idList.add(1L);
        idList.add(2L);
        List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList());
        log.info("去重:{}", JSON.toJSONString(distinctIdList));
10.2 属性去重
        List<Grade> collect = gradeList.stream().filter(distinctByKey(b -> b.getStuNo())).collect(Collectors.toList());
        log.info("去重:{}", JSON.toJSONString(collect));

    //distinctByKey自己定义
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
;