Pass from the list <T> to the input value of the card in Set <T>
I have Map<String,Object>with a record containing a value List<String>. I need to get the content List<String>in 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"));
}
In my Eclipse IDE, there are a few warnings on this line:
- Security Type: uncheck an object from a List object
The compiled code also works as it is intended. Is there a better way to do this? Annotating a string with @SuppressWarnings("unchecked")is my last and least preferred option.
+4
3 answers
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());
}
+8