I have a Map<String,Object>
with an entry that contains a value of List<String>
. I need to get the contents of the List<String>
into a Set<String>
. I am using the following code:
Map<String, Object> map = SomeObj.getMap();
if (map.get("someKey") instance of List<?>) {
Set<String> set = new HashSet<String>((List<String>) map.get("someKey"));
}
My Eclipse-based IDE has a couple of warnings on this line:
The code compiled and runs as it is intended to. Is there a better way to do this though? Annotating the line with @SuppressWarnings("unchecked")
is my last and least preferred option.
You can do the following:
Map<String, Object> map = SomeObj.getMap();
String key = "someKey";
if (map.get(key) instanceof List<?>) {
List<?> list = (List<?>) map.get(key);
Set<String> set = new HashSet<>();
// Cast and add each element individually
for (Object o : list) {
set.add((String) o);
}
// Or, using streams
Set<String> set2 = list.stream().map(o -> (String) o).collect(Collectors.toSet());
}
String
is peculiar, in that a method exists on all objects to convert to it, namely Object.toString()
. Invoking toString()
on a String returns itself.
So, if you know it's a List<?>
, you can convert to a Set<String>
as follows:
List<?> list = (List<?>) map.get("some key");
Set<?> set = list.stream().map(Object::toString).collect(Collectors.toSet());
(You may need to handle null elements)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With