java how to combine two hashmap without duplicate entries - java

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

Related

How to retrieve common key value pairs from two hashmaps

I have two hashmaps:
Map<String, String> mapA = new HashMap<String, String>();
Map<String, String> mapB = new HashMap<String, String>();
TreeSet<String> uniquekeys = new TreeSet<String>();
mapA.put("1","value1");
mapA.put("2","value2");
mapA.put("3","value3");
mapA.put("4","value4");
mapA.put("5","value5");
mapA.put("6","value6");
mapA.put("7","value7");
mapA.put("8","value8");
mapA.put("9","value9");
mapB.put("1","value1");
mapB.put("2","value2");
mapB.put("3","value3");
mapB.put("4","value4");
mapB.put("5","value5");
To get the common key value pairs from the two hashmaps, I have written the below logic:
uniquekeys.addAll(mapA.keySet());
uniquekeys.addAll(mapB.keySet());
and then use the keys from the treeset: uniquekeys to retrieve unique key value pairs from mapA & mapB.
But this is not giving me the details of all the keys from mapA. I understand this way is flawed but I couldn't come up with a proper logic.
Could anyone let me know how can I retrieve key value pairs that are common in mapA and mapB into a new HashMap ?
Try below logic :
Map<String, String> common = new HashMap<String, String>();
for(String key : mapA.keySet()) {
if(mapB.get(key) !=null ) {
if(mapA.get(key).equals(mapB.get(key))) {
common.put(key, mapA.get(key));
}
}
}
You can do it with Java 8 Streams in the following way:
Map<String, String> commonMap = mapA.entrySet().stream()
.filter(x -> mapB.containsKey(x.getKey()))
.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
Instead of adding all keys to a TreeSet, you can fill the TreeSet with common values:
uniquekeys.addAll(mapA.keySet());
uniquekeys.retainAll(mapB.keySet());
This way, the keys contained in A but not B will be removed. Know you've got your TreeSet, you can do what you want.
However, you can also create your HashMap without TreeSet, as #Ramesh and #NiVeR suggest
Use Guava Util Sets
Set<String> intersectionSet = Sets.intersection(firstSet, secondSet);

Display first records in a sorted Map

I'm trying to display first 40 records out of 17K I have stored in a map. I have the following code
import java.util.*;
Map<String, Integer> doubleCount= new HashMap<String,Integer>();
....
Map<String,Integer> newDouble40 = doubleCount.headMap(40);
Java is giving me the following error:
" cannot find symbol - method subMap...
so I tried:
Map<String,Integer> newDouble40 = doubleCount.subMap("",(Integer)40);
and the exact error was:
cannot find symbol - method subMap(java.lang.String,java.lang.int)
http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html
how do I sort?
subMap() and headMap() are two methods in SortedMap those are not available in Map
You can try following way
Map<String, Integer> doubleCount= new HashMap<String,Integer>();
SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount);
Map<String,Integer> newDouble40 = newMap.subMap("0","40");
In your case Keys are String so you need to have String values in subMap("0","40"). 0 is the starting key and "40" is the ending key. Your newDouble40 has element which has a key in between 0 and 40.
Here you can use headMap() as newMap.headMap("40"). now you will get elements which has a key less than 40.
Eg:
Map<String, Integer> doubleCount= new HashMap<>();
doubleCount.put("c",1);
doubleCount.put("d",2);
doubleCount.put("a",1);
doubleCount.put("b",4);
SortedMap<String, Integer> newMap= new TreeMap<>(doubleCount);//sorted now
Map<String,Integer> map1 = newMap.subMap("a", "c");
Map<String,Integer> map2 = newMap.headMap("c");
System.out.println(map1);
System.out.println(map2);
Out put:
{a=1, b=4}
{a=1, b=4}
Main issue here is that you're trying to use methods of a subinterface (java.util.SortedMap), the interface Map doesn't expose either headMap(...) or subMap(...) methods.
A correct code that will compile would be:
SortedMap<String, Integer> doubleCount = new TreeMap<String, Integer>();
Map<String, Integer> newDoubleCount = doubleCount.headMap("40");
One thing you should consider is what is that the methods of the SortedMap returns a portion of the map based on the key argument, compared with the keys in the map, unless you know what is the value of the key of the 40th element, you can't use these methods.

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.

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

What is the best way to create a copy of a Map using pass-by-value?

If I have a Java map with 100s of values in it, and I wanted to create another copy of it using this code :
LinkedHashMap<String, Vector<String>> map1 = new LinkedHashMap<String, Vector<String>>();
LinkedHashMap<String, Vector<String>> map2 = new LinkedHashMap<String, Vector<String>>( map1 );
Then if I change any value in any Vector entry for map1 it will be affected in map2 also. I do not want that. I want map2 to be totally independent on map1.
What is the best way to do that ?
Basically, you'll need to clone each vector:
LinkedHashMap<String, Vector<String>> map2 = new LinkedHashMap<String, Vector<String>>();
for (Map.Entry<String, Vector<String>> entry : map1.entrySet()) {
Vector<String> clone = new Vector<String>(entry.getValue());
map2.put(entry.getKey(), clone);
}
You don't have to go any deeper than that though, of course - because String is immutable.
(Any reason you're using Vector rather than ArrayList, by the way?)

Categories