【问题标题】:How to create a collection and iterator which go through certain values until its reaches one?如何创建一个集合和迭代器,它会遍历某些值直到达到一个值?
【发布时间】:2019-04-12 20:15:50
【问题描述】:

我有一个TreeMap<Token, ArrayList<Token>>,我想遍历地图直到满足要求的特定键。我知道以下方法可用于获取地图的值:

Collection c = bigrams.values();
Iterator itr = c.iterator();

while (itr.hasNext()){
    System.out.println(itr.next());

但是,我希望能够使用链接到迭代器的键来遍历映射,并根据其对键检查每个值。由于bigrams.values() 检索二元组的每个元素的值,我该如何更改它以检索键而不是值?

【问题讨论】:

    标签: java iterator treemap


    【解决方案1】:

    你的问题有点神秘,但是如果你想得到密钥,你可以简单地使用keySet()方法:

    Collection c = test.keySet();
    

    如果你想根据键来遍历地图,你可以这样做:

    for (Token key: bigrams.keySet()) {
        ArrayList<Token> list = bigrams.get(key);
        // do with the list what you want to do with it
    }
    

    【讨论】:

      【解决方案2】:

      您应该选择使用Map.keySet()Map.entrySet()

      Map.keySet() 返回一个包含地图所有键的集合。然后您可以使用Map.get() 来获取给定键的值:

      for (Token key: bigrams.keySet()) {
          List<Token> list = bigrams.get(key);
          System.out.println(key + ": " + list);
      }
      

      Map.entrySet() 返回地图中所有对的集合,因此无需将Map.get() 与此一起使用:

      for (Map.Entry<Token, List<Token>> entry : bigrams.entrySet()) {
          System.out.println(entry.getKey() + ": " + entry.getValue());
      }
      

      最后,您也可以为此使用 Java Stream API。您还可以使用它非常轻松地过滤内容。例如,在其值列表中查找包含给定标记的所有标记:

      bigrams.entrySet().stream()
              .filter(e -> e.getValue().contains(tokenToFind))
              .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-24
        • 2018-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多