This is a simple issue I am just having trouble finding the right terms to use for google help. I have some java code that loops some data and I end up having two pieces of information: an int id, and an int quantity.
However, sometimes the ids are the same, and I want to combine the quantities if they are, rather than having new entries in an array.
In PHP, I would do this as such (assume $products is an array with lots of id/quant data, of course):
$newArray = array();
for($products as $id > $quant){
if(array_key_exists($id, $newArray)){
$newArray[ $id ] += $quant;
} else {
$newArray[ $id ] = $quant;
}
}
I’m trying to do this in Java but nothing I find seems to help.
Use a map implementation, like
HashMap.More or less; adjust types as necessary:
Slightly cleaner to keep the mainline code readable: