class Student_Details{
String name;
int rollNumber;
String address;
// setter and getter of above data members
}
HashMap<String,Collection<Student_Details>> oldData;
HashMap<String,Collection<Student_Details>> newData;
lets say the value in HashMAp oldData is:
abc:[{sam,12,newyork},{mike,15,gotham}]
xyz:[{riphunter,32,new york}]
Hashmap newData contains:
abc:[{sam,12,newyork},{mike,17,London},{john,36,boston]
uvw:[{rip,39,boston}]
Things to do:
1)if key of newData is not present in oldData then add the key value to the oldData
2)if key of newData present in oldData then update the content of the Collection where name should not change .for example the final map(oldData)for above example should have following contents
abc:[{sam,12,newyork},{mike,17,London},{john,36,boston}]
xyz:[{riphunter,32,new york}]
uvw:[{rip,39,boston}]
Please help me with the solution...Thank you
You can use putAll() to achieve
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
I wrote an example here, I use map1 and map2 to simulate your oldData and newData.
putAll() is a wrap for put method which loops put action. Here's the explanation of put()
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Therefore, if key exist, it will update value, otherwise it stores the new key and new value
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
map1.put("a", "1");
map1.put("b", "2");
map1.put("c", "3");
map2.put("a", "10");
map2.put("d", "4");
Map<String, String> temp = new HashMap<>();
temp.putAll(map1);
temp.putAll(map2);
temp.forEach((k,v) -> System.out.println("Key:" + k + ", Value:" +v));
The output is:
Key:a, Value:10
Key:b, Value:2
Key:c, Value:3
Key:d, Value:4
First the key of the map should be the name of the student. Now
Then just do this for every new student
oldMap.put (newStudent.getName(), newStudent);
What it would do is to add the newStudent. If the student with this key doesn't exist then it would be added otherwise, this new value would replace the previous value since its a HashMap which doesn't support duplicate values
Related
My first map
Map< String,Map< String,Object>> accounts = new HashMap< String,Map< String,Object>>();
Example :
{Entry01={DisplayName=Test01, ID=001, Status=A},
Entry01={DisplayName=Test02, ID=002, Status=T},
Entry52={DisplayName=Test52, ID=052, Status=A}}
My second map
Map< String,Set< String>> groupMap = new HashMap< String,Set< String>>();
Example :
{001=[Value01, Value02],
002=[Value08, Value09, Value15],
013=[Value58, Value89, Value90]}
Need to compare both these map and based on the ID key value from first map, I need to get the value from my second map and add it back to my first map with the key name and value.
I tired iterating through map but my map has many entries but only certain entry will have value.
If I understand your problem well, you need to get Set<String> corresponding to ID and add it to the same subMap as the ID :
Iterate throught the pairs
get back the ID
get the Set<String> from the ID
add the set to the value's pair
for (Map.Entry<String, Map<String, Object>> account : accounts.entrySet()) {
Map<String, Object> accountVal = account.getValue();
String id = accountVal.getOrDefault("ID", "").toString();
Set<String> setValues = entitlementMap.getOrDefault(id, Collections.emptySet());
accountVal.put("name", new HashSet<>(setValues));
}
With Code Demo you'll see the following content :
// From
Entry52={Status=A, DisplayName=Test52, ID=052}
Entry01={Status=A, DisplayName=Test01, ID=001}
Entry02={Status=T, DisplayName=Test02, ID=002}
// To
Entry52={Status=A, DisplayName=Test52, ID=052, name=[]}
Entry01={Status=A, DisplayName=Test01, ID=001, name=[Value01, Value02]}
Entry02={Status=T, DisplayName=Test02, ID=002, name=[Value15, Value09, Value08]}
I have method that should return Map<Strings, List<String>> but in the mean time my method gives me a Map<Strings, Object>, I want to transfer the values of object into a List of Strings.
Here is the current code:
#SuppressWarnings("unchecked")
static Map<String, List<String>> getQueryParameters(JsonObject inputJsonObject) {
JsonArray parameters = inputJsonObject.getJsonArray("parameters");
Optional<JsonObject> queryParameters = parameters.stream().
filter(JsonObject.class::isInstance).
map(JsonObject.class::cast).
filter(jsonObject -> jsonObject.getJsonObject("queryParameters") != null).
map(item -> item.getJsonObject("queryParameters")).findFirst();
Map<String, Object> paramMap = queryParameters.get().getMap();
paramMap contains key and value , values could be an arrays of integers
so I want to put them into the map below:
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
My solution is this which did not work correctly
Map<String, List<String>> mystore = new LinkedHashMap<String, List<String>>();
Map<String, Object> paramMap = queryParameters.get().getMap();
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
if (!mystore.containsKey(key)) ;
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
}
I was a key holding another key as value and is just a mix up , any suggestions?
After debuging what happens i see that mystore holds both "key and value" together as a key and value it hold the next "key and value as value
Should be something like this:
while (it.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
String key = next.getKey();
Object value = next.getValue();
if (!mystore.containsKey(key)) mystore.put(key, new LinkedList<String>());
mystore.get(key).add(value.toString());
}
I'm not writing a program for you, but instead help you in finding a problem. You are confused with Entry. If you are using IDE, you should solve it easier. Look for this line :
String key = it.next().toString();
Entry has a K,V pair. The iterator returns an EntrySet and thus usage to get key is it.next().getKey() and it.next().getValue()
Now that you have a correct key, please go on debugging. Instead of putting and getting and manipulating in below lines of your code. Put with correct value instead?
Yours:
mystore.put(key, new LinkedList<String>());
mystore.get(key).add(it.next().toString());
What about?:
Entry entry = it.next();
//Get key and value here. DO coding using Entry's methods
List<String> ll = new LinkedList<String>();
ll.add(value)
mystore.put(key, ll);
Tip: Always have the Javadoc or reference documentation handy for knowing more. That's how you learn the language. Refer:https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.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.
Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
ht.put(1,"student1");
ht.put(1,"student2");
How can I iterate through all values of "a single key"?
key:1
values: student1, student2
You need to use:
Hashtable<Integer, List<String>> ht = new Hashtable<Integer, List<String>>();
and add the new String value for a particular key in the associated List.
Having said that, you should use a HashMap instead of Hashtable. The later one is legacy class, which has been replaced long back by the former.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
then before inserting a new entry, check whether the key already exists, using Map#containsKey() method. If the key is already there, fetch the corresponding list, and then add new value to it. Else, put a new key-value pair.
if (map.containsKey(2)) {
map.get(2).add("newValue");
} else {
map.put(2, new ArrayList<String>(Arrays.asList("newValue"));
}
Another option is to use Guava's Multimap, if you can use 3rd party library.
Multimap<Integer, String> myMultimap = ArrayListMultimap.create();
myMultimap.put(1,"student1");
myMultimap.put(1,"student2");
Collection<String> values = myMultimap.get(1);
A Hashtable doesn't store multiple values for a single key.
When you write ht.put(1, "student2"), it overwrites the value that goes with "1" and it is no longer available.
Hashtable doesn't allow multiple values for a key. When you add a second value to a key, you're replacing the original value.
If you want multiple values for a single key, consider using a HashTable of ArrayLists.
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);