gpt4 book ai didi

java - 根据参数值批量添加List元素

转载 作者:行者123 更新时间:2023-12-02 06:25:48 30 4
gpt4 key购买 nike

private List<PoI> batch(List<PoI> _POIs)
{
List<PoI> _POIs_batched = new ArrayList<PoI>();
for (PoI poi1 : _POIs)
{
for (PoI poi2 : _POIs)
{
if (poi1.getId() == poi2.getId())
{
PoI newPoI = new PoI(poi1.getId(),poi1.getServiceTime()+poi2.getServiceTime());
_POIs_batched.add(newPoI);
}
}
}

return _POIs_batched;
}

我需要查找并批处理具有相同 getId() 值的元素。上面给出的代码的问题是我正在搜索元素对。但是,可能有两个以上的元素具有相同的 getId() 值。如何解决这个问题?

最佳答案

使用 Map<Integer, List<PoI>> (我假设 id 是 int - 或 Integer -键入;无论如何,如果它是 Integer ,请使用 .equals() 而不是 == )。

您可以保留 PoI 的列表共享相同的 id。然后,您可以轻松添加他们的服务时间。

编辑(代码片段):

Map<Integer, List<PoI>> poisPerId = new HashMap<>();
for (PoI poi : _POIs){
Integer id = poi.getId();
List<PoI> pois = poisPerId.get(id);
if(pois == null){
pois = new ArrayList<PoI>();
poisPerId.put(id, pois);
}
pois.add(poi);
}

关于java - 根据参数值批量添加List元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545238/

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