BruceyBandit :
Is there a way to combine two hashmaps into a third third hashmap?
Example:
Hashmap 1 has {key1, value1}, {key2, value2}, {key3, value3)
Hashmap 2 has {key1, value1}, {key2, value2}
Hashmap 3 has {key1, value1}, {key2, value2}, {key3, value3), {key1, value1}, {key2, value2}
Below is an example code:
Map<String, Object> body1 = new HashMap<>();
Map<String, Object> body2 = new HashMap<>();
Map<String, Object> body = new HashMap<>();
table.getTableRows().forEach(row -> {
String value = row.getCell(VALUE);
String field = row.getCell(FIELD);
if (body1.containsKey(field)) {
body2.put(field, value);
} else {
body1.put(field, value);
}
});
//Append both hashmaps into one - body
Arvind Kumar Avinash :
You can have only one value with the same key i.e. you can not have {key1, value1}
twice or more. Whenever you will add an entry with key1
, it will replace the old value of key1
.
If you want to keep both the maps in one collection, you need to use a different collection e.g. List
. Given below is a demo using List
:
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String args[]) {
Map<String, Object> body1=Map.of("key1","value1","key2","value2","key3","value3");
Map<String, Object> body2=Map.of("key1","value1","key2","value2");
List<Map<String, Object>> body=List.of(body1,body2);
for(Map<String, Object> map:body) {
System.out.println(map);
}
}
}
Output:
{key1=value1, key2=value2, key3=value3}
{key2=value2, key1=value1}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=335494&siteId=1