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.
Related
With a LinkedHashMap, when I try to reinsert same key with different value, it replaces the value and maintains the order of key i.e if I do this
Map<String,String> map = new LinkedHashMap<>();
map.put("a", "a");
map.put("b", "b");
map.put("c", "c");
map.put("d", "d");
map.values().stream().forEach(System.out::print);
Output: abcd
Now if I add in the map a different value with same key,the order remains the same i.e
map.put("b", "j");
map.values().stream().forEach(System.out::print);
Output: ajcd
Is there any other way? One is to remove and reinsert key with new value, which prints acdj as output. In my case I want to do it for multiple keys based on some property of object used as value?
Solution using streams would be preferable.
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map
LinkedHashMap javadoc.
it keep track of the keys insertion, and if we add the Map.put javadoc :
If the map previously contained a mapping for the key, the old value is replaced by the specified value.
Map javadoc
The Entry is not replace, only the value is modified so the key remains the same.
You need to remove and then insert the value to update the ordering of the keys.
A HashMap is not sorted by either keys or values. What you are looking for is a TreeMap.
For a HashMap, the only guarantee is, that the keys are hashed and put in an array, based on their hash.
The LinkedHashMap, according to the Javadoc, creates an internal LinkedList, and tracks the original insertion order of entries. In other words, if you use LinkedHashMap, you won't, necessariely receive a 'sorted' list at all.
You have two options to work around this: Either use a TreeMap (or derivate thereof), or sort every time, you want to output the values. TreeMaps have an internal sorting, based on their keys. If the keys are compared to each other the way you'd expect (by comparing the Strings) then you get a properly ascending sorting, based on the keys. However this does not solve your problem, that you want to sort the values.
To solve your original problem, use a bidirectional TreeMap. Apache Commons4 implements such a map (https://commons.apache.org/proper/commons-collections/javadocs/api-4.3/org/apache/commons/collections4/bidimap/AbstractDualBidiMap.html#values--)
It allows you to access both a key and a value set. But be aware that this map will not work for you, if your values are not unique. Like keys, all values in a bidirectional map need to be unique, because they need to serve as keys themselves.
From the Javadoc:
This map enforces the restriction that there is a 1:1 relation between keys and values, meaning that multiple keys cannot map to the same value. This is required so that "inverting" the map results in a map without duplicate keys. See the put(K, V) method description for more information.
Hashmap insertion is based on hashcode only. For example a key of "b" has a hashcode as 98.
for map.put("b", "b");
you inserting as a key "b" which has hascode 98.
so it will look like. 98 ---> holds value 'b'.
again if you try to put on same key "b" which has a hashcode 98 only.
so hashmap try to link on same hashcode only which is 98 ---> holds "j" as a value.
for know working of hashmap hashcode check out below link
https://www.geeksforgeeks.org/internal-working-of-hashmap-java/
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 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.
I am have the Hashmap like this,
HashMap<String,String> epnSource = new HashMap<String, String>();
Now I have added the keys/values like this,
epnSource.put("10.3.2.227","EPN1");
epnSource.put("10.3.2.227","EPN2");
epnSource.put("10.3.2.166","EPN3");
epnSource.put("10.3.2.166","EPN4");
epnSource.put("10.3.2.161","EPN5");
I am trying to do every time before adding a value, I want to check number of occurrences of a key present in the HashMap. Suppose if key 10.3.2.227 has more than two occurrences I shouldn't added it and go for new one. Any suggestions will be helpful.
Suppose if value 10.3.2.227 has more than two occurrences ...
It won't. The way that you have implemented it, the "10.3.2.227" is a key of the Map, and a given key cannot appear more than once in a Map.
If you want a given key (e.g. "10.3.2.227") to map to multiple values (e.g. "EPN1" and "EPN1"), you need to use either a Map<String,Set<String>> or a MultiMap class from the Apache or Google/Guava collections libraries.
If the map previously contained a mapping for the key, the old value is replaced.
It is not possible duplicate key in HashMap.
I'm getting a list of organization type and code are stored as labelvaluebean as below:
[LabelValueBean[ORG1, XX], [ORG2, AA]] - in array.
later these values are stored in a session variable. My question is, is there a way I can search thru this array to match the name and get the code ? (for ex: match with ORG1 and get XX). If user enter ORG1, I should send XX to back-end.
This sounds like you want to be using a Map instead of an array. A Map will store...mappings...between keys and values - think of it like a table with 2 columns, where the first column is your organization type and the second column is the code. You then take an organization code, look in your table at the values in the first column until you find a match, then you look over at the second column for the code, and return it. Obviously, this is handled by the Map implementation used, so all you need to do is declare what Objects should be used as the keys and values. In your case, maybe you'll have a Map<String, String>.
For example,
Map<String, String> map = new HashMap<String, String>();
map.put("ORG1", "XX");
map.put("ORG2", "AA");
map.get("ORG1") // returns "XX"
map.get("ORG2") // returns "AA"