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());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…