How to remove elements of one map from another map? - java

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());

Related

Why <String, String> entry allowed for HashMap<Integer, String>()?

I have HashMap which generic type <Integer, String> i.e. key should be an Integer and value should be String for this HashMap.
I wrote bellow code which put String and getting no compilation and runtime error. Why?
Map map = new HashMap<Integer, String>();
map.put("a", "one");
System.out.println(map);
OUTPUT:
{a=one}
I have HashMap which generic type <Integer, String> ...
No you do not!
Map map = new HashMap<Integer, String>();
Means you have just a Map (because of Map map =). If you want Map<Integer, String> you must use:
Map<Integer, String> map = new HashMap<Integer, String>();
or, in later versions of Java
Map<Integer, String> map = new HashMap<>();
Added
The reason for this is that the right-hand-side of the assignment is a separate process and is evaluated first. In your case it creates a HashMap<Integer, String>.
Next the assignment happens, the compiler checks that HashMap<Integer, String> can be cast to Map (which is equivalent to Map<Object,Object> BTW) and the assignment is performed. From then on all references to map treat it as type Map<Object,Object> and can therefore hold any type for key or value.
You are adding content to Map map declared without specifying any generics types.
If you declare the map this way the compilator doesn't know how to check the map content.
If you change your map declaration to
Map<Integer, String> map = new HashMap<>();
Then you will have a compilation error.
Map map = new HashMap<Integer, String>();
Here your definition is type specified, however declaration is not. So, you are able to add any type to map.
The proper way for generic map declaration is
Map<Integer, String> map = new HashMap<Integer, String>();
or in new versions of Java, you can skip type in defintion.
Map<Integer, String> map = new HashMap<>();
Defining generics on the right side is more or less obsolete (grey font).
Following code wouldn't compile:
Map<Integer, String> map = new HashMap<>();
map.put("a", "one");
System.out.println(map);
with this explanation:
Wrong 1st argument type. Found: 'java.lang.String', required: 'java.lang.Integer'

Add HashMap to another HashMap

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.

java how to combine two hashmap without duplicate entries

I am trying to combine two different hashmaps. But in those two maps, there are some duplicate entries, so I have to remove thoese entries after combine.
For example:
HashMap 1:
100 hello
101 nice
HashMap 2:
100 hello
102 good
After combine, the hashmap should looks like:
100 hello
101 nice
102 good
I have tried putall,but seems it does not remove duplicate entries.
Could someone help me on a fast way to do that?
I don't see a problem in your approach.
HashMap<String, Object> first = new HashMap<String, Object>();
HashMap<String, Object> second = new HashMap<String, Object>();
first.put("100", "hello");
first.put("101", "nice");
second.put("100", "hello");
second.put("102", "good");
first.putAll(second);
System.out.println(first);
outputs
{102=good, 101=nice, 100=hello}
Try to check, if your handling of HashMaps is correct.
The keys of a HashMap can't be duplicates, because they are represented in a Set, so merging the two maps should do the work.
you can add two hashmap map1 and map2 to third hashmap map3 just declare the input type for value as Object as all the data type have their super class as Object class.
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, String> map2 = new HashMap<String, String>();
HashMap<String, Object> map3;
map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);

HashMap from List of Files

I'd like to explore the option of using a HashMap to keep track of changes between files. I'm using a few config/text files to give a set of documents of status:
The config file looks like:
STATUS1 = "Doc1.pdf, Doc2.xls, Doc5.doc"
STATUS2 = "Doc8.pdf, Doc6.doc"
STATUS3 = "Doc10.pdf"
...
Instead of having to create a separate HashMap for each instance like so:
Map<String, String> map1 = new HashMap<String, String>();
Map<String, String> map2 = new HashMap<String, String>();
Map<String, String> map3 = new HashMap<String, String>();
map1.put("STATUS1", "Doc1.pdf");
map2.put("STATUS1", "Doc2.xls");
map3.put("STATUS1", "Doc5.doc");
I'd like to have only a single Map with the key of the status and the values mapped to that key.
I don't need help in parsing the file, I just need assistance in implementing the HashMap or Map so I can add this functionality. If there are other datatypes or methods of organizing this data, I'd like to hear your opinions on that.
Any help would be much appreciated.
You can use a MultiMap, which stores multiple values for the same key.
Multimap
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("STATUS1", "somePDF");
myMultimap.put("STATUS1", "someDOC");
myMultimap.put("STATUS1", "someXCL");
myMultimap.put("STATUS2","someFormat");
// Getting the size
int size = myMultimap.size();
System.out.println(size); // 4
// Getting values
Collection<string> stats1 = myMultimap.get("STATUS1");
System.out.println(stats1); // [somePDF, someDOC, someXCL]
2 . HashMap
With HashMap you can have something like,
List<String> listOfDocs = new ArrayList<String>();
listOfDocs.add("somePDF");
listOfDocs.add("someDOC");
listOfDocs.add("someFormat");
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
// key would be your STATUS
// Values would be ListOfDocs you need.
map.put("STATUS1", listOfDocs);
map.put("STATUS2", listOfDocs2);
map.put("STATUS3", listOfDocs3);
Hope this helps.
Let me know if you have questions.

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.

Categories