映射中值的所有直接键和间接键

时间:2019-07-06 11:16:38

标签: java collections hashmap java-stream

我有一个Map<String, Set<String>>。我的要求是获取特定值的所有直接键和间接键对象。 例如,如果数据如下:

{
 {'Manager'} => ['Jim', 'Michael'],
 {'Jim'} => ['jim.halpert@theoffice.com'],
 {'Fire Marshal'} => ['Manager', 'Dwight'],
 {'Dwight'} => ['dwight.schrute@theoffice.com'],
 {'Michael'} => ['michael.scott@theoffice.com']
}

对于输入'michael.scott@theoffice.com',我应该得到以下输出。

['Michael', 'Manager', 'Fire Marshal']

我尝试了以下代码,但无法正常工作。请帮助我。

 Map<String, Set<String>> addresses;
 String value;//for which we need to search
 Set<String> results = new HashSet<String>();
 Set<String> names;
 do {
    names = addresses.entrySet().stream().filter(entry -> {
         return entry.getValue().contains(value);
    }).map(Map.Entry::getKey).collect(Collectors.toSet());

    results.addAll(names);
 } while (names != null);

1 个答案:

答案 0 :(得分:0)

该程序一直使用相同的搜索值,因此它无休止地运行。下面的代码对我来说很有效,即使它没有按您指定的顺序获得结果顺序,因为我猜发现搜索值的键的顺序也是如此:

    Map<String, Set<String>> addresses;
    String value = "michael.scott@theoffice.com";
    Set<String> results = new HashSet<String>();
    Set<String> names = null;
    do {
      String currentSearchValue;
      if(names != null){
        currentSearchValue = names.iterator().next();
      } else {
        currentSearchValue = value;
      }
      names = addresses.entrySet().stream()
                      .filter(entry -> entry.getValue().contains(currentSearchValue))
                      .map(Map.Entry::getKey).collect(Collectors.toSet());
      results.addAll(names);
    } while (names != null && !names.isEmpty());
  }