I have the following HashMap where the key is String and value is represented by a HashMap.
HashMap<String, HashMap<String, Integer> outerMap = new HashMap<String,HashMap<String, Integer>();
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
innerMap.put("Amount", 2000);
outerMap.put("TutionFee", innerMap);
Now I want to update the value of Amount key. How can I update the value of Amount key?
This should work:
outerMap.get("TutionFee").put("Amount", newValue);
Suppose new value to update is 1000, then outerMap.get("TutionFee").put("Amount", 1000);
Related
I've map of key value pairs with each value being a map of key value pairs.
Something like
Map<String, Map<String, Integer> outMap = new HashMap<>();
Map<String, Integer> inMap = new HashMap<>();
inMap.put("i11", 111);
inMap.put("i21", 121);
outMap.put("o1", inMap);
How would I handle the entry where I can create/update at both levels of the map using java 8 ?
Input would be outer key/inner key and value. So we should we able to add a new entry is it doesn't exist in outer map. If the entry exists in outer map then insert the new entry in inner map if it doesn't exist else update the inner map with new value.
What you want to achieve can be done with this single line of code:
outerMap.computeIfAbsent(outerKey, k -> new HashMap<>()).put(innerKey, value)
But without these methods, you can achieve the same with just get() and put():
Map<String, Integer> innerMap = outerMap.get(outerKey);
if (innerMap == null) {
innerMap = new HashMap<>();
outerMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, value);
HOW TO UPDATE THE SINGLE-VALUE AND MULTIPLE VALUES AT THE SAME TIME SIMULTANEOUSLY IN TWO MAPS
NTOE:
givenMap.computIfAbsent(k,Funtion) -> if key in given map is null or absent, then compute the value using funtion and add into the given map
Map<String, Map<String, Integer>> outMap = new HashMap<>();
Map<String, Integer> inMap = new HashMap<>();
inMap.put("i11", 111);
inMap.put("i21", 121);
outMap.put("o1", inMap);
System.out.println(outMap.toString());
System.out.println(inMap.toString());
OUTPUT BEFORE UPDATING:
{o1={i11=111, i21=121}}
{i11=111, i21=121}
//If you want to add one value in the inner hashmap you created:
outMap.computeIfAbsent("newHashMapKey",k -> new HashMap<>()).put("Arpan",2345);
// if you want to add more than 1 value at a time in the inner hashmap
outMap.computeIfAbsent("newHashMapKey2",k -> new HashMap<>()).putAll(new HashMap<String, Integer>(){{
put("One", 1);
put("Two", 2);
put("Three", 3);
}});
System.out.println(outMap.toString());
System.out.println(inMap.toString());
OUTPUT AFTER UPDATING BOTH MAPS AT THE SAME TIME
{o1={i11=111, i21=121}, newHashMapKey2={Two=2, Three=3, One=1}, newHashMapKey={Arpan=2345}}
{i11=111, i21=121}
I have an outerMap which contains an innerMap for each key it got. At first, every innerMap is the same (here, they contain {1=1}.
I want to change the value of one certain innermap, for a certain key.
Here is my code:
public class HelloWorld
{
public static void main(String args[]){
HashMap<String, HashMap<String, Integer>> outerMap = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
outerMap.put("1001",innerMap);
outerMap.put("1002",innerMap);
outerMap.put("1003",innerMap);
innerMap.put("1", 1);
//My attempt to change only one innermap;
Map<String, Integer> map_to_change = outerMap.get("1001");
map_to_change.put("1", 0);
//And then I print them to see if it's working;
for(Map.Entry map : outerMap.entrySet() )
{
System.out.println(map.getKey()+" "+map.getValue());
}
}
}
However, the output here is
1003 {1=0}
1002 {1=0}
1001 {1=0}
Which shows that my code changes all innermaps, and not only the one linked with the key "1001".
What can I do?
You are pointing the same innerMap object in the outerMap,
outerMap.put("1001",new HashMap<String, Integer>());//create separate maps
outerMap.put("1002",new HashMap<String, Integer>());
outerMap.put("1003",new HashMap<String, Integer>());
HashMap<String, Integer> innerMap =outerMap.get("1001");//get the map you want to put value
innerMap.put("1", 1);//assign the value
Update:
If you want to retain a copy of Map which you have already created, you can copy and create a new Map from it using putAll method,
outerMap.put("1001",copyMap(innerMap));
outerMap.put("1002",copyMap(innerMap));
outerMap.put("1003",copyMap(innerMap));
copyMap method looks like,
private static HashMap<String, Integer> copyMap(HashMap<String, Integer> innerMap){
HashMap<String, Integer> copiedInnerMap = new HashMap<String, Integer>();
copiedInnerMap.putAll(innerMap);
return copiedInnerMap;
}
For instance if I have a map with integer and strings:
Map<Integer, String> myMap = new HashMap<Integer, String>();
This map would contain key values of Integers and values of names.
What I am trying to do is make a new map, that copies all the values (names) from theMap and makes them the keys for the new map. Now the tricky part I can't get, is that I want the values of the new map to be the numbers, but if there are multiple numbers that correspond to the same name I want them to be held in an Set.
Example of new map:
Map<String, Set<Integer>> returnMap = new TreeMap<String, Set<Integer>>();
So if "John" corresponds to 1,2,3,4. I would like the new map to contain a key of "John" with a Set containing 1,2,3,4
Google's Guava library has a nice Multimap class which maps keys to multiple values. If you use it, you can take advantage of a host of helper methods:
SetMultimap<String, Integer> returnMap =
Multimaps.invertFrom(Multimaps.forMap(myMap), TreeMultimap.create());
It's not that tricky :)
Map<Integer, String> map = ... //Your map
Map<String, Set<Integer>> reverseMap = new TreeMap<String, Set<Integer>>();
for(Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
Set<Integer> set;
if(reverseMap.containsKey(value)) {
set = reverseMap.get(value);
set.add(key);
} else {
set = new HashSet<Integer>();
set.add(key);
reverseMap.put(value, set);
}
}
I am adding few item on finalMapNode using map for creating json for d3. and i dont want any duplicates item. how to check.finalmapNode put the duplicates item on map.I dont want duplicated item.if item is avalible then it should not put on map . if id is avalable then item should not put in the finalmapnode.
Note::if id is avalable then item should not put in the finalmapnode.
List<Map<String, Object>> listNodeMap = new ArrayList<Map<String, Object>>();
Map<String, Object> finalMapNode2 = new TreeMap<String, Object>();
Map<String, Object> finalMapNode = new TreeMap<String, Object>();
//if id is avalable then item should not put in the finalmapnode.
finalMapNode.put("id", Integer.parseInt(source2.get(z))+"");
finalMapNode.put("name",source.get(z));
finalMapNode.put("displayname", source.get(z));
finalMapNode.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode.put("type", "location");
finalMapNode.put("group", 0);
finalMapNode.put("opacity", 100);
finalMapNode2.put("id", Integer.parseInt(target2.get(z))+"");
finalMapNode2.put("name",target.get(z));
finalMapNode2.put("displayname", target.get(z));
finalMapNode2.put("image", "/xxxxx/resources/icon/location.png");
finalMapNode2.put("type", "location");
finalMapNode2.put("group", 0);
finalMapNode2.put("opacity", 100);
listNodeMap.add(finalMapNode);
listNodeMap.add(finalMapNode2);
When you try to add the KEY which is already available in the hashmap, then it will override the previous KEY's VALUE and adds the new VALUE. So its up to you to validate the map before trying to add the KEY and VALUE. You can use finalmapnode.containsKey(KEY); to validate and then add the VALUES.
EDIT
Just check the below method works for you!
private static void putMap(String strKey, Object object, Map<String, Object> map){
if(!map.containsKey(strKey)){
map.put(strKey, object);
}
}
In your case, instead of using
finalMapNode.put("name",source.get(z));
you can use
putMap("name",source.get(z), finalMapNode);
The above method will not override the values if you add duplicate KEYS. Pass the KEY, VALUE and the Map which you declared as finalMapNode.
Try this and see.
Thanks!
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "2");
map.put("D", "3");
map.put("E", "3");
HashMap<String, String> mapNew = new HashMap<String, String>();
for(String s :map.keySet())
{
//String value = map.get(s);
System.out.println(s +"=="+map.get(s));
if(!mapNew.containsValue(map.get(s)))
{
mapNew.put(s, map.get(s));
}
}
System.out.println(mapNew);
before :{A=1,B=2,c=2,D=3,E=3}
Output after removing duplicates : {A=1,B=2,D=3}
There is a HashMap:
HashMap aircraftHandling = new HashMap<String, HashMap<Double, Integer>>();
This HashMap contains the following entries:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();
I need to get entries for the key "M", i.e. HashMap<1.22, 200> and HashMap<5.62, 300>. I do this in the following way:
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
The question is how to get Double and Integer, ie (1.22, 200) and (5.62, 300), into two separate variables?
for (int i=0; i<lines.size(); i++)
{
//doubleValue = [i]???
//integerValue = [i]???
}
You can use an enhanced for loop just to read elements :
for (Map.Entry<Double, Integer> entry : lines.entrySet()) {
Double key = entry.getKey();
Integer value = entry.getValue();
}
This HashMap contains the following entries:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();
I need to get entries for the key "M", i.e. HashMap<1.22, 200> and HashMap<5.62, 300>. I do this in the following way:
Not considering the syntax used , since the key is a String , the second time you try to put() a value in the Map using a String key which already exists in Map the new value will override the old value.
This is how you would extract a key-value pair of the HashMap by iterating over a keyset:
Iterator<Double> it= lines.keySet().iterator();
while (it.hasNext()) {
Double key= it.next();
Integer value= lines.get(key);
}
On the side note, I don't know if this is an error, or just a bad representation of your data:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
But if it is how it looks, this is impossible. A Map can have a single value for a single key! That means, if you put some value for a key "M" and you do it again for the same key, the latter will overwrite the previous value. What you should do is:
//get the inner map for "M"
HashMap<Double, Integer> innerMap= aircraftHandling.get("M");
if (innerMap == null) {
//if it does not exist instantiate it
innerMap= new HashMap<Double, Integer>();
aircraftHandling.put("M", innerMap);
}
and now, in the innerMap you add other values, e.g.:
innerMap.put(1.22, 200);
innerMap.put(5.62, 300);
Try maybe this way
Map<Double, Integer> lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
// ^add this generic types here so you wont have to cast them later with getters
for (Map.Entry<Double, Integer> entry:lines.entrySet()){
Double key = entry.getKey();
Integer value = entry.getValue();
}
Here you have it:
HashMap<String, HashMap<Double, Integer>> aircraftHandling = new HashMap<String, HashMap<Double, Integer>>();
HashMap<Double, Integer> subMap1 = new HashMap<Double, Integer>();
subMap1.put(1.22, 200);
HashMap<Double, Integer> subMap2 = new HashMap<Double, Integer>();
subMap1.put(5.62, 300);
aircraftHandling.put("M", subMap1);
aircraftHandling.put("L", subMap2);
HashMap<Double, Integer> lines = aircraftHandling.get("M");
for (Entry<Double, Integer> set : lines.entrySet()) {
Double doubleValue = set.getKey();
Integer integerValue = set.getValue();
}
First, Map can't have duplicate key. If you insert duplicate key then previous one will disappear. You can use following code to separate key and value:
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
for(Map.Entry<Double, Integer> entry: lines ){
doubleValue = entry.getKey();
integerValue =entry.getValue();
}
with a foreach loop and method HashMap.entrySet() :
HashMap<Double, Integer> map=...
for(Entry<Double,Integer> entry : map.entrySet()){
Double d = entry.getKey();
Integer i = entry.getValue();
}
You cannot have 2 values for the key M. I hope you've taken care of that while putting the values. You should have put one hashmap for the value M.
You simply need to fetch the hashmap corresponding to key M
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
And then iterate over all entries in this map
Iterator it = lines.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
double d = pairs.getKey().doubleValue();
int i = pairs.getValue().intValue();
}
EDIT - Had answered from my mobile so missed a few details. Adding them now.