Collections Java8流API用于过滤映射条目

Collections Java8流API用于过滤映射条目,collections,java-8,java-stream,Collections,Java 8,Java Stream,我有一个Java容器,我需要处理它 Map<String, List<Entry<Parameter, String>>> 下面的代码显示了我如何初始化映射结构-有效地将两行放入容器中 Map<String, List<Entry<Parameter, String>>> map2 = new HashMap<String, List<Entry<Parameter, String>>

我有一个Java容器,我需要处理它

Map<String, List<Entry<Parameter, String>>>
下面的代码显示了我如何初始化映射结构-有效地将两行放入容器中

    Map<String, List<Entry<Parameter, String>>> map2 = new HashMap<String, List<Entry<Parameter, String>>>() {{
        put("SERVICE1", new ArrayList<Entry<Parameter, String>>(){{
            add (new AbstractMap.SimpleEntry<>(Parameter.Param1,"val1"));
            add (new AbstractMap.SimpleEntry<>(Parameter.Param2,"val2"));
            add (new AbstractMap.SimpleEntry<>(Parameter.Param3,"val3"));
        }});
        put("SERVICE2", new ArrayList<Entry<Parameter, String>>(){{
            add (new AbstractMap.SimpleEntry<>(Parameter.Param1,"val4"));
            add (new AbstractMap.SimpleEntry<>(Parameter.Param2,"val5"));
            add (new AbstractMap.SimpleEntry<>(Parameter.Param3,"val6"));
        }});
    }};
如果您只需要“val1”和“val2”值,则可以首先使用
getOrDefault
来获取相应的列表,然后对条目的键进行筛选,以获得具有
Param1
Param2
作为键的条目,最后再次应用map来获取这些条目的值

List<String> list =
    myMap.getOrDefault("SERVICE1", Collections.emptyList())
         .stream()
         .filter(e -> e.getKey() == Parameter.Param1 || e.getKey() == Parameter.Param2)
         .map(Map.Entry::getValue)
         .collect(Collectors.toList());
列表=
myMap.getOrDefault(“SERVICE1”,Collections.emptyList())
.stream()
.filter(e->e.getKey()==Parameter.Param1 | e.getKey()==Parameter.Param2)
.map(map.Entry::getValue)
.collect(Collectors.toList());

另外,您可能有兴趣查看

Nice,但是否有某种方法可以实现与当前顶级过滤器(next->next.getKey().equals(“SERVICE1”))中相同的结果,我当前使用的过滤器或总是返回列表列表。我想我写的代码差不多就在那里了,但是有一种方法可以返回这些列表中的第一个。@johnco3是的,使用
flatMap
而不是
map
,并以同样的方式过滤条目
.filter(next->next.getKey().equals(“SERVICE1”).flatMap(e->e.getValue().stream()).filter(e->e.getKey())==Parameter.Param1 | | e.getKey()==Parameter.Param2.map(map.Entry::getValue).collect(…)
。但是使用这种方法没有任何好处,因为您只会有一个列表,因为您对具有特定键的映射感兴趣。。。。除非对键进行筛选可能会导致多个列表,例如
next->next.getKey().startsWith(“SERVICE”)
。是的,您做对了,实际上实际情况是当next.getKey()不是SERVICE1时,我需要筛选不同的参数
    List<List<Entry<Parameter, String>>> listOfLists = myMap.entrySet().stream()
            .filter(next -> next.getKey().equals("SERVICE1"))
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());
    listOfLists.size();
List<String> list =
    myMap.getOrDefault("SERVICE1", Collections.emptyList())
         .stream()
         .filter(e -> e.getKey() == Parameter.Param1 || e.getKey() == Parameter.Param2)
         .map(Map.Entry::getValue)
         .collect(Collectors.toList());