从Map <T>中的Map条目值转换为Set <T>

Web*_*ser 4 java generics

我有一个Map<String,Object>包含值的条目List<String>.我需要把内容List<String>变成一个Set<String>.我使用以下代码:

Map<String, Object> map = SomeObj.getMap();
if (map.get("someKey") instance of List<?>) {

    Set<String> set = new HashSet<String>((List<String>) map.get("someKey"));
}
Run Code Online (Sandbox Code Playgroud)

我的基于Eclipse的IDE在这一行上有几个警告:

  • 类型安全:取消选中从对象到列表的强制转换

代码编译并按预期运行.有没有更好的方法来做到这一点?注释该行@SuppressWarnings("unchecked")是我的最后和最不喜欢的选项.

pkp*_*pnd 8

您可以执行以下操作:

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());
}
Run Code Online (Sandbox Code Playgroud)

  • (请注意,编写地图强制转换的另一种方法是`.map(String.class :: cast)`). (4认同)