我有一个名为HashMap
的{{1}}变量map
是key
而Integer
是value
。
例如,String
中有100个值。我想搜索map
的100个值,然后我想在"Donkey"
中返回Integer
的{{1}},如果没有,则"Donkey"
0.我尝试使用map
循环return Integer
但没有运气。
有人可以给我一个暗示吗?
答案 0 :(得分:4)
试试这个:
int count = Collections.frequency(mapVar.values(), "Donkey");
System.out.println(count);
让我知道它是否有效:)
答案 1 :(得分:0)
Collections.frequency
方法很不错。但是,map.values()
不起作用的断言有点奇怪,因为它应该有效。我想添加它特别奇怪,因为传递给Collections.frequency
的集合是 map.values()
。
// method to do the counting of a particular animal in a map
static Integer countAnimal(String animal, Map<Integer, String> map)
{
int cnt = 0;
for (String val : map.values()) {
if (val.equals(animal)) {
++cnt;
}
}
return new Integer(cnt);
}
public static void main(String[] args)
{
String[] animals = new String[] { "cat", "dog", "pig", "goat", "donkey", "horse", "cow" };
Map<Integer, String> map = new HashMap<>();
// load map for test
Random rnd = new Random();
for (int i = 0; i < 100; ++i) {
String animal = animals[rnd.nextInt(animals.length)];
map.put(new Integer(i), animal);
}
// count how many there are
Map<String, Integer> numAnimals = new HashMap<>();
for (String animal : animals) {
numAnimals.put(animal, countAnimal(animal, map));
}
System.out.println(numAnimals);
// show the cool Collections.frequency approach
Integer count = Collections.frequency(map.values(), "dog");
System.out.println("dog: " + count);
}
示例输出:
{horse = 18,cat = 13,donkey = 23,cow = 15,goat = 17,dog = 3,pig = 11}
狗:3
编辑:允许拆分字符串以查找计数的更新。基本上countAnimal
将拆分从地图中检索到的String,然后检查每个标记以查看它是否是动物。稍微更改了测试用例。它基于更新的评论工作。但是,它没有考虑复数。 “猫”和“猫”的琐碎案例很容易处理,但“鼠标”和“老鼠”会更加困难,需要额外的工作。
public static void main(String[] args)
{
String[] animals = new String[] { "cat", "dog", "pig", "goat",
"donkey", "horse", "cow" };
Map<Integer, String> map = new HashMap<>();
// load map for test
map.put(1, "My friend has a horse");
map.put(2, "A bear can be big"); // will not be found
map.put(3, "A cat is a loner");
map.put(4, "A dog is man's best friend");
map.put(5, "The cat and the dog are peacefully sleeping");
// count how many there are
Map<String, Integer> numAnimals = new HashMap<>();
for (String animal : animals) {
numAnimals.put(animal, countAnimal(animal, map));
}
System.out.println(numAnimals);
}
static Integer countAnimal(String animal, Map<Integer, String> map)
{
int cnt = 0;
for (String val : map.values()) {
// split the val by space
String[] tokens = val.split("[\\s]+");
for (String token : tokens) {
if (token.equalsIgnoreCase(animal)) {
++cnt;
}
}
}
return new Integer(cnt);
}
示例输出:
{horse = 1,cat = 2,donkey = 0,cow = 0,goat = 0,dog = 2,pig = 0}