使用Java Stream API按其值过滤映射



我是Java流的新手,希望使用流运行以下代码。

List<String> roles = new ArrayList<>();
if (stats.containsKey("roles")) {
roles = stats.get("roles");
} else {
Map<String, String> roleMap = stats.containsKey("attributes") ? 
stats.get("attributes") : new HashMap<>();
for (Map.Entry<String, String> e : roleMap.entrySet()) {
if (e.getValue().equals("true")) {
roles.add(e.getKey());
}
}
}

在上面的代码中,我正在执行以下步骤:

  1. 我有一个stats哈希映射,首先我检查roles密钥是否存在,如果存在,我将返回相应的值。

  2. 如果stats散列映射不包含roles密钥,则我正在检查stats散列映射是否包含密钥attributes

  3. 如果CCD_ 7密钥存在,那么它的值是Hashmap;真";,我正在将相应的密钥添加到我的roles列表中。

输入:

{
"attributes":{
"id":false
"name":true
}

}

输出:

["name"]

整个代码可以通过流减少吗?

不确定这会有多大帮助。根据我的说法,在你的用例中使用流并不能简化解决方案,但如果你想使用,那么你可以在你的代码中做这样的事情。

Map<String,Object> stats=new HashMap<>();
List<String> roles = new ArrayList<>();
stats.entrySet().stream()
.forEach(i -> {
if (i.getKey().contains("roles")) {
roles.add((String)i.getValue());
} else if(i.getKey().contains("attributes")){
Map<String, String> roleMap=  (Map<String, String>)i.getValue();
roleMap.entrySet().stream().forEach(j-> {
if (j.getValue()
.equalsIgnoreCase("true"))
roles.add(j.getKey());
});
}
});
stats.keySet().stream().filter(s->s.equals("roles")).findFirst().map(s->stats.get("roles")).orElseGet(()->{
List list=  Lists.newArrayList();
stats.get("attributes").foreach((k,v)->{
if v;list.add(k)
})
return list;
})

如果键rolesattributes的值是相同的类型(List<String>(,您可以很容易地执行类似的操作

List<String> roles = stats.getOrDefault("roles",
stats.getOrDefault("attributes", new ArrayList<>()));

你仍然可以使用这种方法,但由于关联的值是不同类型的,你需要进行一些类型转换,这会使你的代码可能有点不直观:

Map<String, Object> stats = new HashMap<>();
stats.put("roles", Arrays.asList("role1", "role2"));
stats.put("attributes", Map.of("id", "false", "name", "true"));
List<String> roles = (List<String>) stats.getOrDefault("roles",
((Map<String, String>) stats.getOrDefault("attributes", new HashMap<>()))
.entrySet()
.stream()
.filter(i -> i.getValue().equalsIgnoreCase("true"))
.map(Map.Entry::getKey)
.collect(Collectors.toList()));
System.out.println(roles);

最新更新