I have the following code block where I want to convert Map to Map<String,Object>
. Is there a better a way to do what I am trying to achieve
// users -> List<Map>
List<Map<String, Object>> updatedUsers = new ArrayList<>();
for (Map user : users) {
user.put(enclosedListName, removeFromList(data, (List<Map<String, Object>>) user.get(enclosedListName)));
updatedUsers.add(user);
}
someMethod(updatedUsers); //method expects List<Map<String,Object>>, how can i use users directly instead of updatedUsers
You might want to use streams (or you might not!).
However, the main problem is Object
. In general, avoid losing static type information that you are going to need later.
We have List<Map<String, Object>>
. Presumably each element of the List
may have a differently parameterised Map
s. Depending on what you want to do to the Map
there are different options.
If you are just moving about elements within the map and some common method, you can use Map<String, ? extends Common>
Map<String, ? extends Common>
and capture that wildcard:
// Will accept Map<String, ?>
static <T> void swapAB(Map<String, T> map) {
// Odd behaviour involving nulls for this code - ignore that.
T a = map.get("A");
T b = map.get("B");
map.put("A", a);
map.put("B", b);
}
Alternatively, you can wrap the Map
within another object that contains all the methods needed by the client.
interface UpdatedUser {
public void fn(Blah blah);
public void gn(Donkey donkey);
}
public static UpdateUser barUpdateUser(Map<String, Bar> map) {
return new UpdatedUser {
public void fn(Blah blah) {
// Can happily operate on map values.
};
public void gn(Donkey donkey) {
}
};
}
If you want the actual values and there is a fixed set of possibilities, you can perform a kind of switch (a degenerate visitor).
interface UpdateUserSwitch {
void bar(Map<String,Bar> bars);
void foo(Map<String,Foo> foos);
}
In UpdatedUser
:
void swtch(UpdateUserSwitch swtch);
In that anonymous inner class
public void swtch(UpdateUserSwitch swtch) {
swtch(map);
}
(You can add a return type parameter in place of void
if you wish.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.