stream流转map时key值相同value取最大值解决办法

stream流转map遇到key重复value取最大值

最近在处理业务数据的时候需要将集合里面的值按条件赋给另一个集合,相同id赋值进去,同样id对应的值只保留最大值。第一次处理这种情况,所以记录下来。

// 实体类1
@Data
public class Student {

    private Long id;

    private String name;

    private Integer status;

    public Student(Long id, String name, Integer status) {
        this.id = id;
        this.name = name;
        this.status = status;
    }
}
//实体类2
@Data
public class StuDto {

    private Long id;

    private Integer status;

    public StuDto(Long id, Integer status) {
        this.id = id;
        this.status = status;
    }
}

这是添加的数据:

List student = new ArrayList<>();
        student.add(new Student(1L, "小明", null));
        student.add(new Student(2L, "小华", null));
        student.add(new Student(3L, "小白", null));
        student.add(new Student(4L, "小黑", null))

        List dto = new ArrayList<>();
        dto.add(new StuDto(1L, 1));
        dto.add(new StuDto(1L, 2));
        dto.add(new StuDto(1L, 3));
        dto.add(new StuDto(2L, 2));
        dto.add(new StuDto(2L, 4));
        dto.add(new StuDto(3L, 3));
解决思路:key值相同时保留最大值
Map collect = dto.stream().collect(Collectors.toMap(StuDto::getId, s -> s.getStatus(), (k1, k2) -> max(k1, k2)));
    student.forEach(s->
          s.setStatus(Optional.ofNullable(collect.get(s.getId())).orElse(0))
    );

private static Integer max(Integer a, Integer n) {
        if (a > n) {
            return a;
        }
        return n;
    }

你可能感兴趣的:(java)