You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按状态优先级去除ArrayList中id重复的Device对象

实现思路与代码

核心逻辑:给三种状态设置优先级(Complete > Pending > New),将列表按id分组后,每组内仅保留优先级最高的对象即可匹配过滤规则。

Groovy 实现

Groovy语法原生支持集合便捷操作,代码非常简洁:

// 定义状态优先级,数值越大优先级越高
def statusPriority = [complete: 3, pending: 2, new: 1]

// 你的原始Device列表
List<Device> originList = ... 

// 过滤逻辑
List<Device> filteredList = originList.groupBy { it.id }
        .values()
        .collect { sameIdDevices ->
            // 同id分组内取优先级最高的对象
            sameIdDevices.max { statusPriority[it.status.toLowerCase()] }
        }

Java 实现

基于JDK8+ Stream API实现,需要先补全Device类的getter方法:

补全后的Device类

class Device {
    private long id;
    private String name;
    private String status;

    // 按需添加构造方法、setter
    public long getId() { return id; }
    public String getStatus() { return status; }
    public String getName() { return name; }

    @Override
    public String toString() {
        return "Device [id=" + id + ", status=" + status + "]";
    }
}

过滤逻辑代码

import java.util.*;
import java.util.stream.Collectors;

public class DeviceFilter {
    // 状态优先级映射
    private static final Map<String, Integer> STATUS_PRIORITY = Map.of(
            "complete", 3,
            "pending", 2,
            "new", 1
    );

    public static List<Device> filterDuplicates(List<Device> originList) {
        return new ArrayList<>(originList.stream()
                .collect(Collectors.groupingBy(
                        Device::getId,
                        Collectors.collectingAndThen(
                                // 同id分组内选优先级最高的对象
                                Collectors.maxBy(Comparator.comparingInt(device ->
                                        STATUS_PRIORITY.get(device.getStatus().toLowerCase())
                                )),
                                Optional::get
                        )
                ))
                .values());
    }
}

补充说明

如果同id下存在多个相同优先级的对象,上述代码会保留列表中最先出现的那个,如有其他排序要求可自行调整比较器逻辑。

内容的提问来源于stack exchange,提问作者Devs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:45:08