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

标签 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);

最佳答案

该程序始终使用相同的搜索值,因此它运行在无限循环中。下面的代码对我有用,尽管它没有得到您指定的结果顺序,因为我猜是发现搜索值的键的顺序:

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

关于java - 映射中值的所有直接和间接键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913588/

相关文章:

java - Eclipse JUnit 5 支持

java - 用Java编写一个ArrayCalc类,返回最大值、最小值和平均值

java - 如何为名称/值结构创建 JSON 模式?

c# - 如何创建返回集合的 XAML 标记扩展

Java:测试集合中的重复对象

android - 如何将选定的 ListView 项添加到数组列表中

java - Thymeleaf &lt;input&gt; 日期出现 :pattern 错误

Java 集合和垃圾收集器

java - 获取带有注释的所有类并将它们添加到android中的hashMap

java - 从 HashMap 在 Java 中创建 CSV 文件