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.
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]}
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.
Related
EDIT: I have three maps with following format:
map1.put("aaa",1);
map1.put("bbb",1);
map1.put("ccc",1);
map2.put("aaa",2);
map2.put("bbb",3);
map3.put("ccc",6);
map3.put("ddd",6);
Now I want the result as list with following format:
[{"id":"aaa","map1count":"1","map2count":"2","map3count":"0"},
{"id":"bbb","map1count":"1","map2count":"0","map3count":"0"},
{"id":"ccc","map1count":"1","map2count":"0","map3count":"6"},
{"id":"ddd","map1count":"0","map2count":"0","map3count":"6"}]
How can I do this in java, help me to figure out.
you can create a class Count, with three members ex. mapCount1, mapCount2, mapCount3. Now create result map
HashMap<String, Count>() result = new HashMap<>();
Now you need to traverse these 3 maps, check map.containsKey(key), here key might be "aaa", "bbb", "ccc" etc. Now traverse first map, since map doesnt not contain any key, add key with value to result map. Now do this for 2nd, 3rd map, If key is there and then get value of count object and update count for mapCount2/3. At last for each key you can print count specific to each map.
I have a collection say
Map<Integer,Integer> myMap=new Map<Integer,Integer>();
myMap.put(1,"a");
myMap.put(2,"b");
myMap.put(3,"c");
My map currently has {1="a",2="b",3="c"}.
Suppose I want to put a value say myMap.put(1,"d")
So is there a way that I am able to add the existing key and incrementing the remaining key so my output map be like
{1="d",2="a",3="b",4="c"} ?
You will have to iterate over all the elements of the Map in order to modify the values for all the existing keys.
For example, woth Java 8 Streams you can produce a new Map where the keys are incremented, and then add the new Entry :
map = map.entrySet().stream().collect(Collectors.toMap(e->e.getKey()+1,e->e.getValue()));
map.put(1,"d");
However, if your keys are consecutive integers (as your example suggests), why not use an ArrayList<String> instead of a Map<Integer,String>? This will give you the functionality you want by simply calling list.add(0,"d"); (with the small difference of the indices starting at 0 instead of 1).
I have data that is currently being stored in a HashMap<String, ArrayList<HashMap<String, String>>>
I am looking to get a certain value of the ArrayList<HashMap<String, String>>> where the Key is of value "FieldName1". Alternatively, if I try to get the ArrayList Index would it return me both the Key,value pair?
Ultimately what I am trying to do is compare this specific value where the key is "fieldName1" to the other "fieldnName1"'s within the arrayList. If that is the case, should I take the index position of the ArrayList instead?
Thanks!
edit***
The reason HashMap<String, ArrayList<HashMap<String, String>>> is used is because what I am trying to do is process an excel file. I read each row in my excel file and based off the first cell in the row (ex A1) it maps to a certain DB Table. I then have a layoutFile that stores the DB Table name and its corresponding field names. Each new row in that excel file is a different field name.
Alternatively, if I try to get the ArrayList Index would it return me
both the Key,value pair?
This will return the hahsmap object and no the key value pair.
Ultimately what I am trying to do is compare this specific value where
the key is "fieldName1" to the other "fieldnName1"'s within the
arrayList.
Dont know what you meant by this but in a hashmap you cannot have duplicate keys. So you cannot have two "FieldName1" inside the hashmap.
To get the value of "FieldName1" you to traverse the initial hashmap to get the arraylist which contains the hashmap that has the required field. So first get the required arraylist from the hashmap, from the arraylist get the required hashmap and from the hashmap you can get the appropriate field.
I would say you can use the index of the ArrayList, which will return the HashMap object, and then compare the key and value of the one HashMap with the other one's key and value.
Is there a way to put a 2d array into a Hash map setup?
Example of the array would be two strings {"John", "red"},
{"George", "blue}
And I would want red to correspond to john etc.
I know I can use a nested loop to go through every item in the 2d array but how would then set it up to add them to the hash-map
hashMap.put("John", "red");
Assuming every array has 2 items in the form of {Name, Color}, you can just iterate over it
for(String[] combo : some2DArray){
someHashMap.Put(combo[0], combo[1]); // Or swap them, depending on what you
// want to be the key and the value
}
If you want to avoid the possibility of removing data because you happen to have two people with the same name there are a few approaches you can take:
Keep the old data
Keep the new data
Assign the new data to a new key
Combine the data in the same key
Keep the old data
Perform a check before using HashMap#put and see if the key already exists.
Only add the data if it doesn't exist yet.
Keep the new data
Use the current code, it will overwrite the old value.
Assign the new data to a new key
Create a new key based on your own rules and insert that.
Combine the data in the same key
Define your HashMap as HashMap<String, List<String>> and add the values to the list.
How about implementing a Pair class, so you can use HashMap<Pair<String,String>> ?
EDIT: Might be that I misunderstood your question, is that what yoe were asking?
I have a text file which looks like this:
code appearance
----------------
j4t8 1
fj89 3
pf6n 1
j4t8 5
And I want to sort by the codes which appear the most. As you can see (and since I want to perform a group by) there are duplicate codes, so using HashMap would be a problem (duplicate keys). Any ideas?
don't know if this is the best solution but you could create a map of a list like this:
Map<String, List<Integer>> map = new HahsMap<String, List<Integer>>();
if(map.contains.(key))
{
map.get(key).add(new_appearance_value);
}
else
{
List<Integer> app = new ArrayList<Integer>();
app.add(new_appearance_value);
map.put(key, app);
}
Where the map key would be the code and the values of appearance would go into the list.
Note: to determine which code has more appearances just check for the size of the list of each code.
You can use
HashMap map = new HashMap<String, List<Integer>>();
The appearances will be stored in a list associated with every code.
Then given a code you just retrieve the list of integers and iterate over it.
You need a Collection of Pair objects. Each pair holds the code and the appearance. You then sort the collection using a Comparator, which only compares the appearance in each Pair object, and disregards the code.
The Commons Collections MultiValueMap can be used to decorate another map, allowing it to have more than one value for a key.