Reputation: 300
Is there a way to use simple Java for-each loop over Eclipse Collections maps?
I am looking for something like this (but for Eclipse Collections maps):
for (Map.Entry<Integer, String> entry : map.entrySet()) {
}
... but I can't find anything like it for Eclipse Collections maps.
Of course I know this type of Eclipse Collections iterations:
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);
});
}
}
... but this construct has some drawbacks, for example I don't have easy access to the surrounding local variables (as shown in the example above, which example will not compile due to incorrect access to the local variable i
).
Any ideas how to write simple loop over Eclipse Collections maps?
Upvotes: 1
Views: 832
Reputation: 6706
The recommendations from Hulk and Basil in the comments are good. I'll include a test for your code that works for future reference.
@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);
}
The best option is to use an internal iterator as you have in your question, as there will be less garbage generated while iterating (an IntObjectPair for each key/value pair). This comes with the downside of not being able to reference anything from the outer scope of the lambda that is not final. If you want to have a simple counter for things inside of the internal iterator, you can use the Counter
class available in Eclipse Collections.
@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());
}
Upvotes: 4