Add HashMap to another HashMap - java

When i try to add hashMap to another HashMap i lose old varaible. How can i fix this problem? My code is something like that.
HashMap<String, String> tmp = new HashMap<String, String>();
HashMap<String, String> map = new HashMap<String, String>();
tmp = ((HashMap<String, String>)intent.getSerializableExtra("map"));
map.putAll(tmp);
when i use this code map elements always equals tmp elements. It is not stored old elements.
Thanks for help.

HashMap<String, String> map = new HashMap<String, String>(); creates a new, empty, HashMap instance. Therefore after a call to map.putAll(tmp), your map would only contain the entries of tmp.
If map has previous entries, you shouldn't assign a new instance to this variable.
That said, even if map had previous entries, putting the entries of tmp in it would overwrite the values of all the keys that exist in both map and tmp.

Once you have updated map to not be re-initialized every time, you can avoid overwriting any existing key-value pairs in map by looping as follows:
for (String key : tmp.keySet()) {
if (!map.containsKey(key)) {
map.put(key, tmp.get(key);
}
}
I'm not sure from your question if this is exactly what you are asking, but it may be useful. Eran's suggestion (using HashMap<String, List<String>>) is also a good one if you want to store multiple Strings per key.

Related

Create HashMap from HashSet value using loop

I'm trying to create a HashMap from values of a HashSet (which itself is stored as values in a HashMap).
I'm not sure whether to Iterate or use a for loop.
Example:
newMap = new HashMap<String, HashSet<String>>();
HashSet<String> boxing = new HashSet<String>();
newMap.put("fighting", boxing);
boxing.add("jab");
boxing.add("hook");
boxing.add("uppercut");
Now I need to iterate or loop through so that each value in the 'boxing' HashSet creates a new HashMap with the value as the key for the new map.
So newMap1 would have 'jab' as the key, newMap2 would have 'hook' as the key and so on.
Any help is appreciated.
Since Java 9 you can do this:
Map<String, Set<String>> newMap = Map.of("fighting", Set.of("jab","hook","uppercut"));

How to remove elements of one map from another map?

HashMap<String, String> foo = new HashMap<String, String>();
HashMap<String, String> baar = new HashMap<String, String>();
How to remove items found in baar from foo?
You can try:
foo.keySet().removeAll(baar.keySet())
Changes to a Map's keySet() are reflected in the map itself.
If you want to remove exact mappings (not just based on keys), you can use the same approach with the entrySet() instead:
foo.entrySet().removeAll(baar.entrySet());

Java storage and lookup of HashMap in HashSet

I have a set with multi-dimensional hashmaps, like so:
Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();
I am having trouble removing a HashMap entry. I know the key for the top level hashmap, but do not know any data in the underlying hashmap. I am trying to remove a hashmap entry in the set in these ways:
I.
Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();
... Add some hashmaps to the set, then ...
String myKey = "target_key";
setInQuestion.remove(myKey);
II.
Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>();
... Add some hashmaps to the set, then ...
String myKey = "key_one"; //Assume a hashmap has been added with this top level key
HashMap<String, HashMap<String, String>> removeMap = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> dummyMap = new HashMap<String, String>();
removeMap.put(myKey, dummyMap);
setInQuestion.remove(removeMap);
Neither of these methods work. How would I go about removing an entry in the set if I only know the top level hashmap's key?
Collection.remove() requires object equality. the various jdk Map implementations implement equality to mean all keys/values must match. Since none of the objects you are passing to the remove() call would be "equal" to any of the Maps in the Set, nothing is being removed.
the only way to do what you want is to iterate through the Set yourself to find the matching Map (or, make the Set into a Map keyed on that special key).
Thanks jtahlborn for the guidance. Wanted to post the solution I've found as a result of your answer:
String myKey = "Key_In_Question";
Iterator mySetIterator = myHashSet.iterator();
while(mySetIterator.hasNext()) {
HashMap<String, HashMap<String, String>> entry = (HashMap<String, HashMap<String, String>>) mySetIterator.next();
if(entry.containsKey(myKey)) {
myHashSet.remove(entry);
}
}
Sorry I couldn't post this as a comment. I wanted to point out that #jtahlborn's point about Map equality is a well-defined part of the contract... see Map.equals.
... two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Map.Entry.equals is worded similarly.
... two entries e1 and e2 represent the same mapping if
(e1.getKey()==null ?
e2.getKey()==null : e1.getKey().equals(e2.getKey())) &&
(e1.getValue()==null ?
e2.getValue()==null : e1.getValue().equals(e2.getValue()))
This ensures that the equals method works properly across different implementations of the Map.Entry interface.

Creating Hashmap using existing hashmap

I created a hashmap as shown below:
Map<String, String> streetno = new HashMap<String, String>();
streetno.put("3", "Sachin");
streetno.put("2", "Dravid");
streetno.put("1", "Sehwag");
streetno.put("5", "Laxman");
streetno.put("4", "Kohli");
Now I want to create a new hashmap where key of the above hashmap becomes value and value becomes key as shown below:
Map<String, String> streetname = new HashMap<String, String>();
streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");
I don't know how to do that.. Can anyone help me out with this..
Map<String, String> streetname = new HashMap<String, String>();
for (Entry<String,String> e : streetno.entrySet()) {
streetname.put(e.getValue(), e.getKey());
}
Here, the for loop iterates over all entries (i.e. key/value pairs) in the original map, and inserts them into the second map with the key and value swapped over.
It is probably a good idea to check that put() returns null. If you get a non-null value, this means that the values in streetno are not unique. Since this is homework, I leave it to you to figure out the consequences, and how best to handle this.
Perfect you are almost there. Now you need to iterate the first hash map keys and simulate what you have done in those 5 lines:
streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");
Tip: iteration over map might be a bit tricky for you, but usually it is done like that:
for (String key : streetno.keySet()) {
...
}
Good luck with your homework!
Java 8:
Map<String, String> streetname =
streetno.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
Note:
If you are tempted to use parellelstream() instead of stream() think twice about it. This would only be appropriate if your Map is extremely large.

How to retrieve all the values associated with a key?

I want to get all the values associated with a key in Map.
For e.g,
Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC");
tempMap.put("2","RR");
tempMap.put("1","RT");
How to retrieve all the values associated with key 1 ?
the thing you must understand is that in a Map, the key is unique.
that means that after
tempMap.put("1","X");
"1" is mapped to "X"
and after
tempMap.put("1","ABC");
"1" is mapped to "ABC" and the previous value ("X") is lost
From the HashMap javadoc:
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
What you can do is this:
Map<String, List<String>> tempMap = new HashMap<String, List<String>>();
tempMap.put("1", new LinkedList<String>());
tempMap.get("1").add("X");
tempMap.get("1").add("Y");
tempMap.get("1").add("Z");
for(String value : tempMap.get("1")) {
//do something
}
This compartmentalizes values that correspond to the key "1" into their own list, which you can easily access. Just don't forget to initialize the list... else NullPointerExceptions will come to get you.
Yuval =8-)
can't
try using google collections's Multimap
I think you're missing something important:
Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC"); // replaces "X"
tempMap.put("2","RR"); // replaces "Y"
tempMap.put("1","RT"); // replaces "ABC"
Also, you should use generics where possible, so your first line should be:
Map<String, String> tempMap = new HashMap<String, String>();
To do that you have to associate each key with a Set of values, with corresponding logic to create the set and enter/remove values from it instead of simple put() and get() on the Map.
Or you can use one of the readymade Multimap implementations such as the one in Apache commons.

Categories