【问题标题】:All direct and indirect key of a value from map映射中值的所有直接和间接键
【发布时间】:2019-11-16 17:01:47
【问题描述】:

我有一个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);

【问题讨论】:

  • 你的循环总是搜索相同的name - 这显然不是你想要的。您必须检查键值的任何值是否在 names 中 - 最初您必须将 name 添加到 names
  • @AKSW,我该怎么做,因为名称可以有多个值。
  • 确实使用循环吗?

标签: java collections hashmap java-stream


【解决方案1】:

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

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

【讨论】:

  • 嘿@Fana,感谢您的努力。这将解决问题,但只到第二级。但是如何获得所有可能的值。此代码将缺少'Fire Marshal'
  • 当我运行代码时,我得到了以下结果:[Fire Marshal, Manager, Micheal] 所以Fire Marshal 在那里,只是不在你上面​​指定的正确位置。 “直到第二级”是什么意思?
  • @DKAnsh 我编写了代码以产生您在问题中所期望的结果,该问题没有提及超过 2 级
猜你喜欢
  • 1970-01-01
  • 2016-04-08
  • 2021-01-27
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-24
  • 2022-12-14
相关资源
最近更新 更多