可以使用Java 8 的Stream流来实现对list集合的操作。假设有一个名为entityList的List集合,其中Entity是实体类,包含infoId和score两个属性。

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

public class Entity {
    private int infoId;
    private int score;
    
    // getters and setters
    
    public Entity(int infoId, int score) {
        this.infoId = infoId;
        this.score = score;
    }
}

public class Main {
    public static void main(String[] args) {
        // 假设有一个包含实体类的List集合
        List<Entity> entityList = List.of(
                new Entity(1, 100),
                new Entity(2, 200),
                new Entity(1, 150),
                new Entity(2, 250),
                new Entity(3, 300)
        );

        // 使用stream流对实体类进行操作
        List<Entity> result = entityList.stream()
                .collect(Collectors.toMap(
                        Entity::getInfoId, // 使用infoId作为key
                        entity -> entity, // 实体类作为value
                        (entity1, entity2) -> entity1.getScore() > entity2.getScore() ? entity1 : entity2 // 如果出现相同的infoId,保留score最大的实体类
                ))
                .values()
                .stream()
                .collect(Collectors.toList());

        // 输出结果
        result.forEach(entity -> System.out.println("infoId: " + entity.getInfoId() + ", score: " + entity.getScore()));
    }
}

上述代码中,我们首先使用Collectors.toMap方法将List转换为Map,其中key为infoId,value为实体类。在转换的过程中,如果出现相同的infoId,我们使用lambda表达式选择score最大的实体类作为value。

然后,我们再次使用stream流对Map的values进行操作,使用Collectors.toList()方法将结果转换为List,即保留了score最大的实体类。

最后,我们遍历结果List并输出每个实体类的infoId和score。输出结果应该为:

infoId: 1, score: 150
infoId: 2, score: 250
infoId: 3, score: 300
``
使用stream流的方式对于list集合查看实体类里面的相同infoId如果有相同的infoId就保留score最大的实体类其余相同的info的实体类删除

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

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