2016-09-14 48 views
1

我在Java中的以下容器,我需要在的Java 8流API过滤映射条目

Map<String, List<Entry<Parameter, String>>> 

在哪里工作Parameter是定义枚举类型如下:

public enum Parameter { 
    Param1, 
    Param2, 
    Param3 
} 

的下面的代码显示了我如何初始化映射结构 - 有效地将2行放入容器中。

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")); 
     }}); 
    }}; 

我需要使用java 8流API来找到“SERVICE1”的val1val2值,但我不知道正确的Java流过滤器和映射语法。

我能拿出最近的事情是下面的,但在顶级这只过滤器,它返回一个列表的列表,而不是Parameter.Param1,"val1" & Parameter.Param2,"val3",我正在寻找从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(); 

回答

3

如果你只需要“VAL1”和“VAL2”的价值观,你可以先用getOrDefault得到相应的列表,然后在输入键过滤得到与Param1Param2为重点项目,最后再次应用地图来获取这些条目的值。

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()); 

而且你可能有兴趣看看Efficiency of Java "Double Brace Initialization"?

+0

不错,但有没有达到同样的结果在目前的顶级滤波离开(未来的某种方式 - > next.getKey()等于( “SERVICE1”)),我目前已经有或者总是要返回一个列表清单。我认为我写的代码差不多在那里,但是有一些方法可以返回列表中的第一个列表。 – johnco3

+2

@ 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 (...)'。但使用这种方法没有好处,因为您只有一个列表,因为您对使用特定键的映射感兴趣。 –

+2

...除非按键过滤可能导致多个列表,例如'next - > next.getKey()。startsWith(“SERVICE”)'。 –