可以使用 Java 8 的 Stream 流来实现对 List 集合中相同 infoId 的实体类进行筛选和删除操作。下面是一种可能的实现方式:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // 创建包含实体类的 List 集合
        List<Entity> entities = new ArrayList<>();
        entities.add(new Entity(1, 90, 'Alice'));
        entities.add(new Entity(2, 85, 'Bob'));
        entities.add(new Entity(1, 95, 'Charlie'));
        entities.add(new Entity(3, 80, 'David'));
        entities.add(new Entity(2, 75, 'Eve'));
        
        // 使用 Stream 流进行筛选和删除操作
        List<Entity> filteredEntities = entities.stream()
                .collect(Collectors.groupingBy(Entity::getInfoId))
                .values()
                .stream()
                .map(list -> list.stream()
                        .max(Comparator.comparing(Entity::getScore))
                        .orElse(null))
                .filter(entity -> entity != null)
                .collect(Collectors.toList());
        
        // 打印筛选后的结果
        filteredEntities.forEach(System.out::println);
    }
}

class Entity {
    private int infoId;
    private int score;
    private String name;
    
    public Entity(int infoId, int score, String name) {
        this.infoId = infoId;
        this.score = score;
        this.name = name;
    }
    
    public int getInfoId() {
        return infoId;
    }
    
    public int getScore() {
        return score;
    }
    
    public String getName() {
        return name;
    }
    
    @Override
    public String toString() {
        return "Entity{" +
                "infoId=" + infoId +
                ", score=" + score +
                ", name='" + name + "'"
                + '}';
    }
}

上述代码中,首先创建了一个包含实体类 Entity 的 List 集合。然后使用 Stream 流对集合中的实体类进行操作。通过 Collectors.groupingBy(Entity::getInfoId) 将实体类按照 infoId 进行分组,得到一个 Map,其中 key 为 infoId,value 为具有相同 infoId 的实体类的列表。

接下来,使用 values() 方法获取 Map 中的所有 value,即分组后的实体类列表。然后使用 map() 方法处理每个实体类列表,使用 max(Comparator.comparing(Entity::getScore)) 获取 score 最大的实体类,如果列表为空,则返回 null。

最后,使用 filter() 方法过滤掉为 null 的实体类,并使用 collect(Collectors.toList()) 将结果收集为 List 集合。

最后,通过 forEach(System.out::println) 遍历并打印筛选后的结果。

输出结果为:

Entity{infoId=1, score=95, name='Charlie'}
Entity{infoId=2, score=85, name='Bob'}
Entity{infoId=3, score=80, name='David'}

可以看到,根据 infoId 筛选后,保留了 score 最大的实体类。

Java Stream流:如何筛选并删除 List 集合中相同 infoId 的实体类

原文地址: https://www.cveoy.top/t/topic/qEfv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录