如何从一组值中计算HashTable中的冲突数?

时间:2016-12-02 01:26:49

标签: java hashtable

如果给出一组数字值和HashTable大小,我怎样才能模拟碰撞次数?

1 个答案:

答案 0 :(得分:1)

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

这个的简单实现可能是:

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);