我需要找到最有效的方法来从最流行的类别中找到随机元素
从
4 Cheese
1 Olive
2 Mushroom
4 Ham
2 Chicken
4 Salad
我想要要么Cheese
要么。如果有多个顶级类别,我不在乎我会从哪个类别中获得我的物品。Ham
Salad
在输入上我有Iterator<Foo>
whereFoo
实现
Interface Foo {
int getCategory();
}
我当前的代码如下所示:
Foo getItem(Iterator<Foo> it) {
Map<Integer, List<Foo>> categoryMap = new HashMap<Integer, List<Foo>>();
while(it.hasNext()) {
Foo foo = it.next();
int category = foo.getCategory();
List<Foo> l = categoryMap.get(category);
if(l == null) {
l = new ArrayList<Foo>();
categoryMap.put(category, l);
}
l.add(foo);
}
int longest_list_size = 0;
int longest_category_id = -1;
Set<Integer> categories = categoryMap.keySet()
for(Integer c: categories ) {
int list_size = categoryMap.get(c).size();
if(list_size > longest_list_size) {
longest_list_size = list_size;
longest_category_id = c;
}
}
if(longest_list_size == 0)
return null;
int r = new Random().nextInt(longest_list_size);
return categoryMap.get(c).get(r);
}