I have two HashMap, first one has 3149 records and the second one 5440 records, when I combine them, the result size is smaller then 3149+5440. Why and how can i solve it?
Map<String,String> bigMap = new HashMap<String, String>();
bigMap.putAll(hashMap1);
bigMap.putAll(hashMap2);
int j = 0;
for (Map.Entry<String, String> entry : bigMap.entrySet()) {
System.out.println(j++);
}
I also cheched with this code to be sure if there is some common key.
for (Map.Entry<String, String> entry : readCsv(hashMap1).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(entry.getKey().equals(hashMap2).get(key))){
System.out.println(i++);
}
}
Your hashMap1 and hashMap probably have a number of same keys. That's why some entries are overridden by other entries with similar keys.
If you have the same keys in the maps, then this is to be expected. Keys must be unique in a map. If you put a value into the map with a key that already exists, then the existing value is overwritten.
To find the common keys you can do
Set<String> common = new HsahSet<String>(hashMap1.keySet());
common.retainAll(hashMap2.keySet());
System.out.println("Common Keys " + common);
Related
I have an HashMap with names(key) and dates(value) and I need to show if a name that i enter again is a duplicate (I am doing socket programming with different states). Example, I put in the map 3 different names and at the forth time I put a duplicate name.
I tried these codes (they run) but with no success:
HashMap<String, String> map = new HashMap<String, String>();
if(stat.equals("RECEIVE_NAME")){
name = reader.readLine();
if(map.containsKey(name)){
System.out.println("duplicate");
}
}
or
for(Map.Entry<String, String> entry : map.entrySet()){
if(name.equals(entry.getKey())){
sendMessage("duplicate");
}
}
NB: I have a map.put(name) when is not a duplicate after this sequence of blocks. And i know that an hash map can not have duplicate keys :)
A HashMap cannot contain duplicate keys. If you put a key-value pair in a map which already contains the key, the old value will be replaced by the new value.
map.put() returns the previous value associated with key, or null if there was no mapping for key. So you can store that return value and check if is not null:
String check = map.put(name);
if(check != null){
System.out.println("dup: " + check);
}
Use map.putIfAbsent(name) to not overwrite the associated value.
Hi I am working with HashMap in java and i have a scenario where i have to compare 2 HashMaps
HashMap1:
Key: BOF Value: SAPF
Key: BOM Value: SAPM
Key: BOL Value: SAPL
HashMap2:
Key: BOF Value: Data1
Key: BOL Value: Data2
And after comparing these two hashmaps my resulting hashmap will contain the Key as a Value of First HashMap1 and Value as a Value of second HashMap2.
HashMap3:
Key: SAPF Value: Data1
Key: SAPL Value: Data2
Just iterate on the keys of HashMap1, and for each key, check if it's present in HashMap2.
If it's present, add the values to HashMap3 :
final Map<String, String> hm1 = new HashMap<String, String>();
hm1.put("BOF", "SAPF");
hm1.put("BOM", "SAPM");
hm1.put("BOL", "SAPL");
final Map<String, String> hm2 = new HashMap<String, String>();
hm2.put("BOF", "Data1");
hm2.put("BOL", "Data2");
final Map<String, String> hm3 = new HashMap<String, String>();
for (final String key : hm1.keySet()) {
if (hm2.containsKey(key)) {
hm3.put(hm1.get(key), hm2.get(key));
}
}
Iterate over the keys of the first map and put the values in your new map, if the second map has a value for the same key.
Map map3 = new HashMap();
for (Object key : map1.keySet()) {
Object value2 = map2.get(key);
if (value2 != null) {
Object value1 = map1.get(key);
map3.put(value1, value2);
}
}
HashMap has an method called entrySet() that returns an object that represents the content of the map as a set of key-value pairs.
public Set<Map.Entry<K,V>> entrySet()
You should iterate through that set using the keys to look up in the second map and then putting the results in the 'result set'.
I assume you have a established that the values in the first set will be unique OR you don't mind that entries might get overwritten in the output.
Notice that the iterator moves through the set in an unspecified order so if there are overwrites this method won't guarantee which values overwrite which other values.
You can use the keySets of both maps to intersect them using:
boolean retainAll(Collection<?> c)
and then iterate using that intersection over the tho maps building your solution.
I am using Map as follows
Map<String, String> propMap = new LinkedHashMap<String, String>();
and I saw that there is two methods that I can use keySet() (to get the list of keys)
and values to get the list of values but my question is how to relate between them
for example for key1 the value is 2.
I thought to use get value like follows
Map<String, String> propMap2 = propterm.getPropMap();
Set<String> keySet = propMap2.keySet();
But how I relate it to his respective value ?
You can use propMap.entrySet() method which returns a Map.Entry of key, value, if you want to use every pair of key and value: -
for (Map.Entry<String, String> entry: propMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
Or, if you want to know how to do this with propMap.keySet(), you can iterate over the Set<Key> you obtain, and for each key, use propMap.get(key), to get the value of a particular key: -
Set<String> keySet = propMap2.keySet();
for (String key: keySet) {
System.out.println(propMap.get(key));
}
From an answer from this post: -
With the later approach, if you are regularly accessing the key-value pair, then for each key, the map.get() method is called, which - in the case of a HashMap - requires that the hashCode() and equals() methods of the key object be evaluated in order to find the associated value*. In the first case (entrySet), that extra work is eliminated.
Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.
Map.put(DATE, value1);
Map.put(VALUE, value2);
arraylist.put(Map);
Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist? i have tried this
if(!list.isEmpty()){ // list is an ArrayList
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
}
Log.d(TAG, "map size is" + map.size());
String [] keys = new String[map.size()];
String [] date_value = new String[map.size()];
String [] value_values = new String[map.size()];
int i = 0;
Set entries = map.entrySet();
Iterator iterator = entries.iterator();
while(iterator.hasNext()){
Map.Entry mapping = (Map.Entry)iterator.next();
keys[i] = mapping.getKey().toString();
date_value[i] = map.get(keys[i]);
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
i++;
}
But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks
Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key: map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
Also, your 1st for-loop looks odd to me: -
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.
EDIT: -
You can also use entrySet if you want both key and value for your map. That would be better bet for you: -
Map<String, Integer> map = new HashMap<String, Integer>();
for(Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
Try it this way...
I am considering the HashMap with key and value of type String, HashMap<String,String>
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("key1","Val1");
hmap.put("key2","Val2");
ArrayList<String> arList = new ArrayList<String>();
for(Map.Entry<String,String> map : hmap.entrySet()){
arList.add(map.getValue());
}
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());
Put i++ somewhere at the end of your loop.
In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.
FYI: the below is doing a redundant search:
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
replace with
if(keys[i].equals(DATE)){
date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){
value_values[i] = mapping.getValue()
}
Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.
This is incredibly old, but I stumbled across it trying to find an answer to a different question.
my question is how do you get the values from both map keys in the arraylist?
for (String key : map.keyset()) {
list.add(key + "|" + map.get(key));
}
the Map size always return a value of 2, which is just the elements
I think you may be confused by the functionality of HashMap. HashMap only allows 1 to 1 relationships in the map.
For example if you have:
String TAG_FOO = "FOO";
String TAG_BAR = "BAR";
and attempt to do something like this:
ArrayList<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> map = new HashMap<>();
for (String bar : bars) {
map.put(TAG_BAR, bar);
}
This code will end up setting the key entry "BAR" to be associated with the final item in the list bars.
In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.
Suppose I have Hashmap with key datatype as KeyDataType
and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Java 8 solution for produce string like "key1: value1,key2: value2"
private static String hashMapToString(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.joining(","));
}
and produce a list simple collect as list
private static List<String> hashMapToList(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.toList());
}
It has method to find all values from map:
Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
Iterate over vs to do some operation
I have a HashMap, which contains another HashMap. I want to iterate over the first HashMap and use the Key values from that. Then, as I iterate over the first HashMap I want to start an inner loop iterating over the second HashMap, getting all the values.
The problem I have so far is that I can't figure out how to get the keys from the Iterator.
HashMap<String, HashMap<Integer, String>> subitems = myHashMap.get("mainitem1");
Collection c = subitems.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
// Get key somehow? itr.getKey() ???
// contains the sub items
HashMap productitem = (HashMap)itr.next();
}
The data that i get from subitems is this:
{Item1{0=sub1, 1=sub2}, Item2{0=sub3, 1=sub4}}
Then, in the while loop productitem contains the 'sub items'. But i can't find out where i can get the key value 'Item1' and 'Item2' from.
How can i get those?
You can't get the key from values().iterator().
You need to use entrySet().iterator(). That will return Map.Entry<K,V> objects on which you can call getKey() and getValue().
for (Map.Entry<Integer,Key> entry : subitems.keySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
// do stuff
}
I'd also like to add that having deeply nested maps of lists of maps is usually a sign that you really want to write custom classes to hold your data. Especially when the maps have pre-defined keys to be used and interpretation of the values in the lists depends on the position within the list! I call this code smell "object denial".
You can't go from value to key in a map. (There may be several keys mapping to the same value!)
You can iterate over the map entries though using subitems.entrySet().iterator(), or you can iterate over the keys, and in each iteration retrieve the associated value through subitems.get(key).
You could do something like this (using iterators):
Set<Entry<String, HashMap<Integer, String>>> c = subitems.entrySet();
Iterator<Entry<String, HashMap<Integer, String>>> iterator = c.iterator();
while(iterator.hasNext())
{
Entry<String, HashMap<Integer, String>> entry = iterator.next();
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
Iterator<Entry<Integer, String>> innerIterator = innerMap.entrySet().iterator();
while (innerIterator.hasNext()) {
Entry<Integer, String> innerEntry = innerIterator.next();
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
or like this using foreach structure:
for (Entry<String, HashMap<Integer,String>> entry : subitems.entrySet())
{
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
for (Entry<Integer, String> innerEntry : innerMap.entrySet())
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
java Collections provide facility of EntrySet. This is a list of objects which contain individual keys and values as its properties. You can take a iterator out of this list.
You can get keys as follows.
Iterator i= subitems.entrySet().iterator();
while(i.hasNext()){
String key= i.next().getkey();
}
You can iterate over entries using entrySet().iterator() on the first HashMap or get the keys and iterate over them: Instead of subitems.values().iterator() use subitems.keys().iterator() and use the next key to get the inner hashmap.