【问题标题】:Simple loop iteration over Eclipse Collections maps (for example: IntObjectHashMap)Eclipse Collections 映射上的简单循环迭代(例如:IntObjectHashMap)
【发布时间】:2021-05-01 13:12:48
【问题描述】:

有没有办法在 Eclipse Collections 映射上使用简单的 Java for-each 循环?

我正在寻找类似的东西(但对于 Eclipse Collections 地图):

for (Map.Entry<Integer, String> entry : map.entrySet()) {
}

...但我在 Eclipse Collections 地图中找不到类似的东西。

我当然知道这种类型的 Eclipse Collections 迭代:

import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap;

public class Test {
    public static void main(String[] args) {
        IntObjectHashMap<String> map = new IntObjectHashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        int i = 0;
        map.forEachKeyValue((int key, String val) -> {
            i++; // Compilation error. 
            System.out.println("key: " + key + ", val: " + val);
        });
    }
}

...但是这种构造有一些缺点,例如我无法轻松访问周围的局部变量(如上例所示,由于对局部变量@987654326的错误访问,该示例将无法编译@)。

任何想法如何编写简单循环覆盖 Eclipse Collections 地图?

【问题讨论】:

  • 我还没有使用过 Eclipse 集合,但从文档中可以看出 IntObjectHashMap.keyValuesView() 在地图中的条目上返回一个 Iterable(在这种情况下为 IntObjectPair-instances)。应该可以在增强的 for 循环中使用它。
  • 看起来很有前途!非常感谢你,绿巨人。

标签: java loops foreach iterator eclipse-collections


【解决方案1】:

在 cmets 中 Hulk 和 Basil 的建议很好。我将为您的代码添加一个测试,以供将来参考。

@Test
public void keyValuesView()
{
    IntObjectHashMap<String> map = new IntObjectHashMap<>();
    map.put(1, "one");
    map.put(2, "two");
    int i = 0;
    for (IntObjectPair<String> pair : map.keyValuesView())
    {
        i++;
        System.out.println("key: " + pair.getOne() + ", val: " + pair.getTwo());
    }
    Assert.assertEquals(2, i);
}

最好的选择是使用内部迭代器,就像您在问题中所使用的那样,因为迭代时生成的垃圾会更少(每个键/值对都有一个 IntObjectPair)。这带来了无法从 lambda 的外部范围引用非 final 的任何内容的缺点。如果您想为内部迭代器内部的事物创建一个简单的计数器,可以使用 Eclipse Collections 中的 Counter 类。

@Test
public void forEachKeyValueWithCounter()
{
    IntObjectHashMap<String> map = new IntObjectHashMap<>();
    map.put(1, "one");
    map.put(2, "two");
    Counter counter = new Counter();
    map.forEachKeyValue((int key, String val) -> {
        counter.increment();
        System.out.println("key: " + key + ", val: " + val);
    });
    Assert.assertEquals(2, counter.getCount());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2014-06-29
    • 2020-12-16
    • 2015-06-05
    • 1970-01-01
    相关资源
    最近更新 更多