代码之家  ›  专栏  ›  技术社区  ›  rainer

Java用SimpleEntry在地图上迭代

  •  0
  • rainer  · 技术社区  · 7 年前

    我有一个树状图,有3个条目,类型如下:

    Map<String, Entry<String, String>> treeMap = new TreeMap<String, Entry<String, String>>();
    

    我用以下代码填充地图:

    SimpleEntry<String, String> simpleEntry = new SimpleEntry<String, String>("", "");
    
    for (int i = 0; i < listSites.size(); i++) {
    
            String stringkey = listSites.get(i);
            String stringValue = listSitesDesc.get(i);
            String stringLink = listSitesLinks.get(i);
    
            entry = new SimpleEntry<String, String>(stringValue, stringLink);
            actionMap.put(stringkey, simpleEntry);
    
    }
    

    我的问题是如何从排序树映射中检索单个值。

    编辑时间:

    for (Map.Entry<String, Entry<String, String>> entrySet : treeMap.entrySet()) {
    
            String key = entrySet.getKey();
            String valueKey = simpleEntry.getKey();
            String valueValue = simpleEntry.getValue();
    }
    

     key = one , two , three , four , five ..... 
    

    但是我得到了valueKey和valueValue的错误值,比如:

    valueKey = bear , bear , bear , bear , bear ...
    

    valueKey = dog , cat , monkey, tiger , bear ....
    

    我做错什么了?

    4 回复  |  直到 7 年前
        1
  •  4
  •   Bohemian    7 年前

    Map.keySet() (毫不奇怪)返回 钥匙 价值观 .

    为了得到 价值观 Map.values() .

    迭代所有键/值对,即 条目 :

    for (Map.Entry<String, Entry<String, String>> entry : treeMap.entrySet()) {
        // showing how to get at the parts:
        String key = entry.getKey();
        String valueKey = entry.getValue().getKey();
        String valueValue = entry.getValue().getValue();
    
    }
    

    这是解决任何问题的一种不寻常的方法,因为每个键只有一个值,所以您有“key->键->值”,与“keykey”相同->价值观”。考虑省去外层贴图,只使用 Map<String, String> ,和/或使用带有(命名)字段的类来存储数据。

        2
  •  0
  •   Paul    7 年前

    我不明白你的问题。。。

    简单地说?

    因为不清楚你到底在寻找什么(这可能就是你找不到答案的原因),这里有一些(但不是全部)迭代地图的方法:

    // I'm changing your map a little to avoid confusion over the word 'Entry'.
    Map<String, SimpleEntry<String, String>> treeMap = new TreeMap<>();
    for (Map.Entry<String, SimpleEntry<String, String>> ent: treeMap.entrySet())
    {
      String key = ent.getKey();
      SimpleEntry val - ent.getValue();
    }
    

    // Using your original map
    Map<String, Entry<String, String>> treeMap = new TreeMap<>();
    treeMap.forEach((key, value) ->
    {
      // key is a String, value is an Entry<String, String>>
    });
    
    // Explicit parameter types can increase code readability
    treeMap.forEach((String key, Entry<String, String>> value) ->
    {
      // Have fun with the contents of your map!
    });
    
    
        3
  •  0
  •   DefyGravity    7 年前

    首先,接受@Bohemian的回答,这就是你想要的。以及任何未来的谷歌。它不起作用是因为您有一个bug:D(这就是为什么我们都会出现堆栈溢出,这取决于您对bug的定义)

    ...

    );