I have two HashMap
objects defined as:
Map<String, String> requestParams = new HashMap<>();
Map<String, Boolean> requestParamForOauth = new HashMap<>();
How can I merge these two maps?
I have two HashMap
objects defined as:
Map<String, String> requestParams = new HashMap<>();
Map<String, Boolean> requestParamForOauth = new HashMap<>();
How can I merge these two maps?
Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example.
You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.
The only downside is that there is no "official" Pair class that you could use (see here for more thoughts around that).
Alternatively, if there is a "deeper" meaning of those "combined" values (beyond a simple "tuple/pair" semantics), you could instead create your own class that wraps around those two values.
Your keys are of the same type (String), but the values are not even related by an interface or super class, you will need to define a Map<String, Object>
and make use of the Map#putAll
method
Map<String, String> requestParams = new HashMap<>();
Map<String, Boolean> requestParamForOauth = new HashMap<>();
Map<String, Object> requestParamForOauth2 = new HashMap<>();
requestParamForOauth2.putAll(requestParams);
requestParamForOauth2.putAll(requestParamForOauth);
If you want to use one list to store all the data You can
use one HashMap<String,Object>
What do you want to do when the same key appears in both Map
? If you want to keep both the String
and Boolean
, then you'll need a map that looks like this: Map<String, Pair(String, Boolean)>
. If you just want to keep one value, then Map<String, Object>
is what you want.