Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate fastutil hashmap in Java8?

In Java8, want to compare time performance and memory consumption of Int2ObjectOpenHashMap (fastutil library) and HashMap<Integer, MyObj> in my app. Previously I iterated java standard hashmap as below:

HashMap<Integer, MyObj> myobjs = new HashMap<Integer, MyObj>();
// fill myobjs in
for (Map.Entry<Integer, MyObj> obj : myobjs.entrySet()) {
    ...
} 

How can I iterate (in the fastest possible way) the Int2ObjectOpenHashMap?

like image 560
Brandon McHomery Avatar asked Feb 09 '23 05:02

Brandon McHomery


1 Answers

There is the specialized fastForEach() on the entry set, which, to gain extra performance, instead of recreating an entry instance for every loop cycle, reuses the entry instance of type Int2ObjectMap.Entry<MyObj>:

Int2ObjectOpenHashMap<MyObj> int2ObjHashMap = ...;
int2ObjHashMap.int2ObjectEntrySet().fastForEach((Int2ObjectMap.Entry<MyObj> entry) -> {
    int key = entry.getIntKey();
    MyObj value = entry.getValue();
    // ...
});

By using the int-specific methods int2ObjectEntrySet() and getIntKey() instead of entrySet() and getKey(), this code also avoids the unnecessary inboxing and outboxing of the entry's key to/from int and Integer.

like image 146
Daniel S. Avatar answered Feb 24 '23 15:02

Daniel S.