Reputation: 81
I am writing program which reads data from excel file which contains following two columns:
1- Unit code 2- quantity
Unit Code contains all units which maybe repeated also. I want to add all quantities present for same unit code without loosing any of them. I want to store this whole data in hashmap.
Please help me out.
Thanks in Advance.
Upvotes: 1
Views: 607
Reputation: 185
You can store your data in a HashMap
. The 'unit' can be taken as keys and the sum of 'quantities' as values. You can insert a key-value pair in your HashMap
as soon as you find a 'unit' first time. Corresponding quantity will be stored as value. Now again when inserting the next record from excel, check if the new 'unit' already exists in the HashMap
. If yes then the new 'quantity' should be summed to the corresponding value. If no, then a new entry will be put in the map.
The code is as follows:
Map<String,Integer> map=new HashMap<>();
//Open the file for reading using some excel API
//Read the unit and quantity line by line and assign them in `unit` and `quantity` variables
String unit=""; // Read actual unit value from file
int quantity=0; // Read actual quantity value from file
if(map.containsKey(unit)){
map.put(unit, map.get(unit)+quantity);
}
The map does not allow duplicate keys. So when you again put the same key in the map, it will overwrite the existing entry in the map. Thus the resultant map will contain the units and the sum of corresponding quantities as entries.
Upvotes: 1
Reputation: 35557
You can't put duplicate keys in HashMap
. But you can try something like this
Map<Key,List<Values>> map=new HashMap<>();
Now there can be list of values for selected key.
Eg:
Map<String,List<String>> map=new HashMap<>();
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("b");
map.put("a",list);
System.out.println(map);
Output:
{a=[a, b, b]}
Upvotes: 3