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.
Related
I have a HashTable with the following {4:1, 3:56, 4:3, 4:5, 9:89, etc.}
I then make the keys of this Table into a keyset by calling map.keySet().
How can I loop through that set to only output the values associated with the key of 4? I want the output to be 1,3,5, therefore I only want the values associated with the key 4? Is this possible, and if so how.
That's not how maps work. Maps typically only associate one value with each unique key value. So if you have a Map<Integer,Integer> myMap, calling myMap.put(4, newValue), where newValue is some integer, will overwrite the value that was previously mapped to 4. You can have duplicate values though, and you can print all known keys that have been mapped to that value in a map using the following loop.
for (Entry<Integer, Integer> entry : myMap.entrySet()) {
if (entry.getValue().equals(4)) {
System.out.println(entry.getKey());
}
}
A HashMap or a HashTable only maps a key to a value.
Option 1:
If you want to have multiple values for key store it as a list
Map<Integer, List<Integer>> myMap = new HashMap<>();
//To add value for a key
if (!myMap.containsKey(key)) {
myMap.put(new ArrayList<>());
}
myMap.get(key).add(value);
//Get
myMap.get(key); //This will give you the list of value for a given key and null if the key is not present
Option 2:
You can use Google Guava's MultiMap
You can use Google Guava Collections' MultiMap as it allows each key to associate with multiple values.
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put(key, value);
Documentation can be found here: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html
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 a bit confused. i was reading the map interface. It has to use entrySet() method for collection view to use iterator. entrySet() return a Set that contains the elements of map. Again, each of this Set element is a Map.Entry object. how is that possible? as Set contains only one field, whereas Map.Entry is a key value pair?
A map is basically a set of key => value mappings. In addition, the keys are unique and the values don't have to be. A key-value pair is encapsulated within a Map.Entry object. When you iterate over the entries of a map (= the set of key-value pairs), for each entry you can get the key with entry.getKey() and the value with entry.getValue().
In addition to the set of entries, a map also provides the set of keys, and the collection of values. For example, in a Map<String, Date>, you have the set of key-value pairs as Set<Map.Entry<String, Date>>, the set of keys as Set<String> and the collection of values as Collection<Date>.
A concrete example of iterating over entries:
Map<String, Date> map = new HashMap<String, Date>();
map.put("now", new Date());
map.put("now+", new Date());
for (Map.Entry<String, Date> entry : map.entrySet()) {
String key = entry.getKey();
Date value = entry.getValue();
System.out.println(String.format("%s => %s", key, value));
}
Another way to iterate is by keys:
for (String key : map.keySet()) {
Date value = map.get(key);
System.out.println(String.format("%s => %s", key, value));
}
But this is less efficient because for each key you have to perform a lookup to get the value, in contrast with using entries with direct access to values.
Set elements are objects, Map.Entry instance is also an object. All correct.
Consider the following: You can create your own Cat class with whichever properties you like. E.g.:
public class Cat {
private String name;
private String type;
private boolean isGrumpy;
// etc...
}
As long as you implement equals(Object) and hashCode(), instances of this class can be put in a Set, right?
So why should Map.Entry be different? Just think of it as a class with two members - key and value.
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);
If .NET has a SortedDictionary object ... what is this in Java, please? I also need to be able to retrieve an Enumeration (of elements), in the Java code .. so I can just iterate over all the keys.
I'm thinking it's a TreeMap ? But I don't think that has an Enumeration that is exposed?
Any ideas?
TreeMap would be the right choice. As for the Collection of all the keys (or values), any Map exposes keySet() and values().
EDIT (to answer your question with code tags). Assuming you have a Map<String, Object>:
for (String key : map.keySet()) {
System.out.println(key); // prints the key
System.out.println( map.get(key) ); // prints the value
}
You can also use entrySet() instead of keySet() or values() in order to iterate through the key->value pairs.
TreeMap is probably the closest thing you're going to find.
You can iterate over the keys by calling TreeMap.keySet(); and iterating over the Set that is returned:
// assume a TreeMap<String, String> called treeMap
for(String key : treeMap.keySet())
{
string value = treeMap[key];
}
It would be the equivalent of:
// assume a SortedDictionary called sortedDictionary
foreach(var key in sortedDictionary.Keys)
{
var value = sortedDictionary[key];
}
You could also try the following:
// assume TreeMap<String, String> called treeMap
for (Map.Entry<String, String> entry : treeMap.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
}
Which is the equivalent to the following .NET code:
// assume SortedDictionary<string, string> called sortedDictionary
foreach(KeyValuePair<string, string> kvp in sortedDictionary)
{
var key = kvp.Key;
var value = kvp.Value;
}
What you need is entrySet() method of SortedMap (TreeMap).