gpt4 book ai didi

java - 构建一个新数组以根据公共(public)索引组织数据

转载 作者:行者123 更新时间:2023-11-29 06:06:27 25 4
gpt4 key购买 nike

这是一个简单的问题,我只是无法找到用于 google 帮助的正确术语。我有一些循环一些数据的 Java 代码,我最终得到两条信息:一个 int id 和一个 int quantity。

但是,有时 ID 相同,如果数量相同,我想合并这些数量,而不是在数组中添加新条目。

在 PHP 中,我会这样做(假设 $products 是一个包含大量 id/quant 数据的数组,当然):

$newArray = array();
for($products as $id > $quant){
if(array_key_exists($id, $newArray)){
$newArray[ $id ] += $quant;
} else {
$newArray[ $id ] = $quant;
}
}

我正在尝试用 Java 执行此操作,但我发现似乎无济于事。

最佳答案

使用 HashMap :

1. Get the id
2. See if the id is present in the map
3. if not
insert (id, quantity)
else (i.e. if present)
quantity = hashmap.get(id);
quantity = quantity + new_quantity
hashmap.put(id, quantity);

有帮助吗?

有很多方法,hashmaps占用更多内存。您也可以使用 2 个数组执行此操作,但这样您将花费更多时间来搜索数组。

关于java - 构建一个新数组以根据公共(public)索引组织数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8390656/

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