Reputation: 55
When multiple keys have same hash code, then a collision occurs. In that case, key-value entries are stored in linked list format mapping to a bucket. Now I wish to know how many such Map.Entry pair exists for given bucket. Is there any inbuilt java method that would help me to identify?
bucket1 ----> (10, 1) ---> (100, 2) --- Answer is 2 in this case.
bucket2 ----> (2, 1) ---- Answer is 1.
bucket3 ----> (3, 5) ---> (6, 10) ---> (9, 15) ---> (12, 18) ---- Answer in this case 4.
Any help towards this would be great.
Upvotes: 0
Views: 198
Reputation: 141
Unless you're using a collection as the value for your map, you won't be able to have more than one value for a particular bucket. Check what put()
will do in the docs for HashMap
Using a list as value for your map, you can try the following:
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Playground {
public static void main(String[] args) {
Map<Integer, List<Pair>> map = new LinkedHashMap<Integer, List<Pair>>();
map.put(1, Arrays.asList(new Pair(10, 1) , new Pair(100, 2)));
map.put(2, Arrays.asList(new Pair(2, 1)));
map.put(3, Arrays.asList(new Pair(3, 5), new Pair(6, 10), new Pair(9, 15), new Pair(12, 18)));
for (Map.Entry<Integer, List<Pair>> entry : map.entrySet()) {
System.out.println(String.format("Bucket %d has %d item(s)", entry.getKey(), entry.getValue().size()));
}
}
}
class Pair {
Integer x;
Integer y;
Pair(Integer x, Integer y) {
this.x = x;
this.y = y;
}
}
Your output will be the following:
Bucket 1 has 2 item(s)
Bucket 2 has 1 item(s)
Bucket 3 has 4 item(s)
Hope that helps
Upvotes: 2