gpt4 book ai didi

java - 我们可以使用Java在Map中一次放入多个键和值吗

转载 作者:行者123 更新时间:2023-12-01 07:02:01 26 4
gpt4 key购买 nike

这就是我所做的。我有一个要转换为映射的对象列表,其中键作为对象 id,值作为对象。我的列表中有数千个对象,这导致了性能问题。有没有简单的方法可以在不使用循环或使用其他数据集的情况下完成此操作?

final List<Object> objects = new ArrayList<Object>();
final Map<Id, Object> objectMap = new HashMap<Id, Object>();

for (final Object object : objects)
{
objectMap.put(object.getId(), object);
}

最佳答案

您可以尝试使用正确的容量和负载因子来优化HashMap:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

容量的最佳值是n/lf,因此添加元素不会触发重新哈希,其中n是最大元素计数,lf负载系数。默认负载因子为 0.75,但您可以在构造函数中设置它以满足您的需要。

The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

默认值使您的 map 通过如此多的放置操作多次重新散列元素,这会影响性能

循环是强制性的,由您或收集器创建。

关于java - 我们可以使用Java在Map中一次放入多个键和值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42690022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com