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
source share
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
source

String , , Object.toString(). toString() .

, List<?>, Set<String> :

List<?> list = (List<?>) map.get("some key");
Set<?> set = list.stream().map(Object::toString).collect(Collectors.toSet());

(, )

+3

You cannot "distinguish" from List <> to Set <>; these are different interfaces with different methods. But you can do instead ...

Set<String> set = new HashSet<String>();
set.addAll(map.get("someKey"));

This takes advantage of the addAll Collection interface.

-2
source

Source: https://habr.com/ru/post/1696368/


All Articles