【问题标题】:Get the map keys and not the map values [duplicate]获取地图键而不是地图值[重复]
【发布时间】:2013-05-20 00:32:30
【问题描述】:

我有一些这样的数据:

Map<Integer, String> foo

现在我可以用foo.get(1)得到对应的String

但是是否也可以获取所有具有String“abc”的Integers?

喜欢这个伪代码:Integer[] someMore = foo.getKeys("abc")

【问题讨论】:

  • 为此,您需要创建自己的实现来查找具有特定值的键... :)
  • 您可以遍历地图并检查某个键的值是否 == 您要查找的字符串,然后将其添加到数组列表中
  • 如果是这样的用例,那么你创建的Map不正确,你需要交换key和value。
  • 你看过这个:stackoverflow.com/questions/4005816/… 吗?
  • 您必须遍历地图并找到具有给定值的所有键。但是,这远没有相反的效率那么高。见stackoverflow.com/a/46908/17713

标签: java


【解决方案1】:
Map<Integer, String> map = new Map<Integer, String>();
ArrayList<Integer> arraylist = new ArrayList<Integer>();
for (Entry<Integer, String> entry : map.entrySet()) {
    if (entry.getValue().equals("abc")) {
    arraylist.add(entry.getKey());
    }
}

【讨论】:

    【解决方案2】:

    普通地图无法做到这一点。您必须调用 foo.entrySet() 并自行创建数组。

    也许您会对使用双向地图感兴趣。这是一个线程,您可以在其中阅读一些相关信息。 Bi-directional Map in Java?

    【讨论】:

      【解决方案3】:

      Map 不提供按值查找。我们需要通过迭代 Map 条目来做到这一点

      Set<Integer> matchingKeys =  new HashSet<Integer>();
      for(Entry<Integer, String> e : map.entrySet()) {
          if(e.getValue().equals("abc")) {
                matchingKeys.add(e.getKey());
          }
      }
      

      【讨论】:

        【解决方案4】:

        试试:

        Set<Integer> myInts = new HashSet<Integer>();
        for(Entry<Integer, String> entry : foo.entrySet()) { // go through the entries
            if(entry.getValue().equals("abc")) {             // check the value
                myInts.add(entry.getKey());                  // add the key
            }
        }
        // myInts now contains all the keys for which the value equals "abc"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-16
          相关资源
          最近更新 更多