Performance: Creating an ArrayList from HashMap.values()

后端 未结 5 1372
感动是毒
感动是毒 2021-02-12 10:32

Question is how much it costs to create an ArrayList from a HashMap.values() Collection? Or creating the values Collection alone? Assuming Map.size() > 100k. Objects could also

5条回答
  •  深忆病人
    2021-02-12 11:22

    HashMap internally stores values in a Collection values. Take a look at the source code of AbstractMap, the parent of HashMap.

    So HashMap.values() directly returns a Collection. There is no computation or data copying done. It's as fast as it can be.

    Just get the values and then do a for loop:

    int n = 5;  // every 5th element
    Object[] values = hashMap.values().toArray();
    int size = values.length;
    for (int i = 0; i < size; i += n){
       values[i];
       // do something
    )
    

提交回复
热议问题