FastUtil fast map iterators

39 views
Skip to first unread message

JBoss JatMan

unread,
Feb 9, 2024, 6:22:26 AMFeb 9
to fastutil
Hi,

I've been looking through the documentation for information about what operations (such as remove) are available when iterating over a map. I haven't found a definitive answer there...I'm hoping someone here can answer.

My question is, when using a fast for-each iterator, can I safely remove the current item? Can I safely remove other items ensuring that I don't see duplicate keys or have missing keys?

Eg. Sample code below, which creates a map of 10000 items, and removes a third of them whilst iterating. It confirms that all of the values were seen once and only once.

    static class Tester implements LongConsumer {
        Long2ObjectOpenHashMap<String> _map;
        LongOpenHashSet _seenValues = new LongOpenHashSet();


        Tester(Long2ObjectOpenHashMap<String> map) {
            _map = map;
        }


        @Override
        public void accept(long key) {
            if (_seenValues.contains(key)) {
                System.out.println("Duplicate value at: " + key);
            }

            _seenValues.add(key);

            String it = _map.get(key);
            if (!it.equals(""+key)) {
                System.out.println("Invalid value at: " + key);
                return;
            }

            if ((key % 3)==0) {
                _map.remove(key);
            }
        }
    };


Test:
        Long2ObjectOpenHashMap<String> map = new Long2ObjectOpenHashMap<>();

        for (int i=0; i<10000; ++i) {
            map.put(i, "" + i);
        }
        Tester tester = new Tester(map);
        map.keySet().forEach(tester);
        if (tester._seenValues.size()!=10000) {
            System.out.println("VALUES MISSING: " + (10000 - tester._seenValues.size()));
        }
System.out.println(map.size());



Thanks
JBoss

Sebastiano Vigna

unread,
Feb 9, 2024, 7:34:25 AMFeb 9
to fast...@googlegroups.com
That's not a question about fastutil. It's pretty normal you can't find it in the documentation. It's a question about the semantics of iterators of Java Collections.

You can remove the current item. That's why there's a remove method. Any other concurrent alteration of the state of the map leads to unpredictable behavior.

JBoss JatMan

unread,
Feb 9, 2024, 9:14:48 AMFeb 9
to fastutil
Hi Sebastiano,

Yes, I suppose I wasn't sure if the faster "forEach" methods worked with removal as the "iterator" is hidden.

Thanks for clarifying it for me!

JBoss

Reply all
Reply to author
Forward
0 new messages