我无法在ArrayList中找到最常用和最少使用的String。该程序应该通过一个字符串文件,并计算列表中有多少个字符串。然后在列表中打印最少和最常用的名称。 ArrayList部分已完成。它只是找到了我遇到麻烦的最常见和最不常见的名字。我不知道如何开始它。这是我在网上找到的,但它不起作用。
Map<String, Integer> dogNames = new HashMap<>();
for (Dog dog : dogs) {
Integer value = dogNames.get(dog);
if (value == null) {
value = 0;
}
value++;
dogNames.put(dog.getName(), value);
}
int leastCommon = Integer.MAX_VALUE;
String leastCommonName = null;
for (String name : dogNames.keySet()) {
int value = dogNames.get(name);
if (value < leastCommon) {
leastCommon = value;
leastCommonName = name;
}
}
System.out.println("Least common (" + leastCommon + ") is " + leastCommonName);
答案 0 :(得分:1)
您的代码问题似乎在这一行:
Integer value = dogNames.get(dog);
你的地图上有狗的名字(String
),但你得到的Dog
条目不存在!因此,即使您之前看过该名称,value
也会保留0
。如果你解决了这个问题,你的代码应该可行。
您可以根据地图中的计数定义自定义Comparator
,而不是使用搜索最不常用名称的循环,然后使用Collections.min
和Collections.max
:
Comparator<Dog> comp = new Comparator<Dog>() {
@Override
public int compare(Dog o1, Dog o2) {
return Integer.compare(dogNames.get(o1.getName()), dogNames.get(o2.getName()));
}
};
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
使用Java 8,您可以使用Comparator.comparing
:
List<Dog> dogs = ...
Map<String, Integer> dogNames = new HashMap<>();
dogs.forEach(dog -> dogNames.put(dog.getName(), dogNames.getOrDefault(dog.getName(), 0) + 1));
Comparator<Dog> comp = Comparator.comparing(d -> dogNames.get(d.getName()));
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
甚至更短,使用Collections.frequency
而不是构建自己的地图,并使用它进行比较。但请注意,如果列表很长,这将是浪费,因为这将每次重新搜索列表而不是缓存地图中的计数。
List<Dog> dogs = ...
Comparator<Dog> comp = Comparator.comparing(d -> Collections.frequency(dogs, d.getName()));
System.out.println("least " + Collections.min(dogs, comp));
System.out.println("most " + Collections.max(dogs, comp));
答案 1 :(得分:0)
您的代码看起来应该是这样的......
Map<String,int> frequencyOfDogNames = new HashMap<String,int>();
for(String dogName:dogNames) {
if(frequencyOfDogNames.contains(dogName)) {
continue;
}
frequencyOfDogNames.put(dogName, Collections.frequency(dogs, "dogName"));
}
这将为您提供所有具有出现次数的名称的地图。
现在我们应该循环思考地图,看看哪一个是最大值和最小值......
int leastCommon = Integer.MAX_VALUE;
int mostCommon = 0;
String leastCommonName, mostCommonName;
int occurrence;
for(String dogName: frequencyOfDogNames.keySet()) {
occurrence = frequencyOfDogNames.get(dogName);
if(leastCommon > occurrence){
leastCommon = occurrence;
leastCommonName = dogName;
}
if(mostCommon < occurrence){
mostCommon = occurrence;
mostCommonName = dogName;
}
}