Java 如何从一组值计算哈希表中的冲突数?

Java 如何从一组值计算哈希表中的冲突数?,java,hashtable,Java,Hashtable,如果给定一组数值和哈希表大小,如何模拟冲突数?计算集合中数值的哈希值,并计算重复哈希值的数量 这方面的一个简单实现可能是: List<Integer> yourValues = /* Your set of numbers */; Map<Integer, Set<Integer>> map = new HashMap<>(); // Insert all elements into buckets based on their hash valu

如果给定一组数值和哈希表大小,如何模拟冲突数?

计算集合中数值的哈希值,并计算重复哈希值的数量

这方面的一个简单实现可能是:

List<Integer> yourValues = /* Your set of numbers */;
Map<Integer, Set<Integer>> map = new HashMap<>();
// Insert all elements into buckets based on their hash value
yourValues.forEach(value -> {
    if (!map.containsKey(value.hashCode()))
        map.put(value.hashCode(), new HashSet<>());
    map.get(value.hashCode()).add(value);
});
// Sum up the number of values in each bucket, subtract the number of buckets, so only duplicate values are counted
int collisions = map.values().stream().map(Set::size).reduce(0, Integer::sum) - map.size();
System.out.printf("Number of collisions: %d\n", collisions);
列出您的值=/*您的一组数字*/;
Map Map=newhashmap();
//根据散列值将所有元素插入到桶中
yourValues.forEach(值->{
如果(!map.containsKey(value.hashCode()))
map.put(value.hashCode(),new HashSet());
map.get(value.hashCode()).add(value);
});
//将每个存储桶中的值的数量相加,减去存储桶的数量,因此只计算重复的值
int collisions=map.values().stream().map(Set::size).reduce(0,Integer::sum)-map.size();
System.out.printf(“冲突数:%d\n”,冲突);

到目前为止您做了哪些研究?冲突的数量取决于您的哈希算法,因此没有一个适合所有人的答案。谢谢您。然而,我对yourObjects是什么数据类型有点困惑。你能澄清一下吗?这是整数值的集合。可能是一个列表或集合。我改变了答案。