您可以使用地圖建議由某人在評論部分。見工作示例:
import java.util.HashMap;
import java.util.Map;
public class HelloWorld {
public static void main(String []args){
Map<String, Integer> myMap = new HashMap<String, Integer>();
String[] products = {"Apple", "Pear", "Banana", "Apple"};
String[] amounts = {"2", "3", "3", "2"};
for (int i = 0; i < products.length; i++) {
String product = products[i];
int amount = Integer.valueOf(amounts[i]);
if (myMap.containsKey(product)) {
myMap.put(product, myMap.get(product) + amount);
} else {
myMap.put(product, amount);
}
}
for (String product : myMap.keySet()) {
System.out.println(product + ": " + myMap.get(product));
}
}
}
參考:https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
創建一個地圖'',你的產品名稱映射到(的總和)金額。 –
Smutje
其實我有兩件事要做。首先,我需要找到具有相同價值的產品元素並對它們進行分組。其次,我需要獲得每個產品組的數量。例如,我們有product = {「Apple」,「Pear」,「Banana」,「Apple」},amount = {2,3,3,2}。然後分組後,它們應該是product = {「Apple」,「Pear」,「Banana」},amount = {4,3,3} –
'final String product = products [i]; final Integer amount = Integer.valueOf(amount [i]); if(map.contains(product)){map.put(map.get(product)+ amount;} else {map.put(amount);}' – Smutje