Map map = new HashMap(collection.size());for (Object obj : collection) { map.put(obj.key, obj.value);}
The code above wants to make sure that the HashMap doesn’t need to be resized, so its sets the initial size to the number of elements that it will use. But, the HashMap implementation doesn’t behave like this, it sets its internal threshold to threshold = (int)(capacity * loadFactor), this means that it will resize after 75% of the collection has been inserted into the map, causing extra garbage. Avoid this using the code below:
Map map = new HashMap(1+ (int) (collection.size() / 0.75));
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.






















