There are two maps: Master Map and Modified Map.
if modifiedmap.key == mastermap.key
then set mastermap.value = modifiedmap.value
Here is what doing right now
for (Map.Entry<String, String> entry : modified_map.entrySet())
{
for(Map.Entry<String,String> entry1:master_map.entrySet())
{
if(entry.getKey().equalsIgnoreCase(entry1.getKey()))
{
entry1.setValue(entry.getValue());
}
}
}
I am using two nested loops.
How ever map has a method called containsKey()
so I was try to use master_map.containsKey()modified_map) then assign the value
however i am not getting how to get mastermap Value corresponding to the matching key while trying to do with a single loop
something like this
for (Map.Entry<String, String> entry : modified_map.entrySet())
{
if(master_map.containsKey(entry.getKey()))
then get the corresponding value then swap it
}
If I understood correctly, you need something like this:
for (Map.Entry<String, String> entry : modified_map.entrySet()) {
if (master_map.containsKey(entry.getKey())
master_map.put (entry.getKey(),entry.getValue());
}
This would modify the value of each entry in master_map that has a key that appears in modified_map.
V put(K key,
V value)
Associates the specified value with the specified key in this map
(optional operation). If the map previously contained a mapping for
the key, the old value is replaced by the specified value. (A map m is
said to contain a mapping for a key k if and only if m.containsKey(k)
would return true.)
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.
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 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.
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).
I'm using Guava's ArrayListMultimap<K,V> collection to map Integers to Strings. The class provides a method called containsValue(Object value) which checks if the Multimap contains the specified value for any key. Once I determine that is true, what's the best way to retrieve said key?
ArrayListMultimap<String, Integer> myMap = ArrayListMultimap.create();
if (myMap.containsValue(new Integer(1))
{
// retrieve the key?
}
Instead of using containsValue you could iterate over myMap.entries() which returns a collection of all key-value pairs. The iterator generated by the returned collection traverses the values for one key, followed by the values of a second key, and so on:
Integer toFind = new Integer(1);
for (Map.Entry<String, Integer> entry: myMap.entries()) {
if (toFind.equals(entry.getValue())) {
// entry.getKey() is the first match
}
}
// handle not found case
If you look at the implementation of containsValue it just iterates over the map's values so the performance of doing this with map.entries() instead of map.values() should be about the same.
public boolean containsValue(#Nullable Object value) {
for (Collection<V> collection : map.values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
In the general case of course there isn't necessarily a unique key for a given value so unless you know that in your map each value only occurs against a single key you would need to specify the behaviour e.g. if you wanted the first key or last key.