gpt4 book ai didi

java - 将对象值列表转换为组

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:36 26 4
gpt4 key购买 nike

我有如下一段代码

OrderCriteria o1 = new OrderCriteria(1, 1, 101, 201);
OrderCriteria o2 = new OrderCriteria(1, 1, 102, 202);
OrderCriteria o4 = new OrderCriteria(1, 1, 102, 201);
OrderCriteria o5 = new OrderCriteria(2, 2, 501, 601);
OrderCriteria o6 = new OrderCriteria(2, 2, 501, 602);
OrderCriteria o7 = new OrderCriteria(2, 2, 502, 601);
OrderCriteria o8 = new OrderCriteria(2, 2, 502, 602);
OrderCriteria o9 = new OrderCriteria(2, 2, 503, 603);

OrderCriteria 如下所示:

public class OrderCriteria {
private final long orderId;
private final long orderCatalogId;
private final long procedureId;
private final long diagnosisId;

public OrderCriteria(long orderId, long orderCatalogId, long procedureId, long diagnosisId) {
this.orderId = orderId;
this.orderCatalogId = orderCatalogId;
this.procedureId = procedureId;
this.diagnosisId = diagnosisId;
}

// Getters
}

我想要的是获取按订单 ID 分组的程序列表和诊断列表。所以它应该返回:

{1, {101, 102}, {201, 202}}
{2, {501, 502, 503}, {601, 602, 603}}

这意味着 ID 为 1 的订单具有过程 ID 101、102 和诊断 ID 201、202 等。我尝试使用 google guava 表但无法提出任何有效的解决方案。

最佳答案

首先,您需要一个新结构来保存分组数据:

class OrderCriteriaGroup {
final Set<Long> procedures = new HashSet<>();
final Set<Long> diagnoses = new HashSet<>();

void add(OrderCriteria o) {
procedures.add(o.getProcedureId());
diagnoses.add(o.getDiagnosisId());
}

OrderCriteriaGroup merge(OrderCriteriaGroup g) {
procedures.addAll(g.procedures);
diagnoses.addAll(g.diagnoses);
return this;
}
}

add()merge() 是帮助我们流式传输和收集数据的便捷方法,如下所示:

Map<Long, OrderCriteriaGroup> grouped = criteriaList.stream()
.collect(Collectors.groupingBy(OrderCriteria::getOrderId,
Collector.of(
OrderCriteriaGroup::new,
OrderCriteriaGroup::add,
OrderCriteriaGroup::merge)));

关于java - 将对象值列表转换为组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com