java - 在不使用 HashMap 的情况下查找排序的 ArrayList 中最常见的字符串

标签 java arrays sorting arraylist counter

考虑包含 StringArrayList

animalsArray[dog, cat, dog, dog, cat, duck, duck, dog]

我可以轻松地使用 HashMap 来查找最常见的 String,使用 HashMap 值作为计数器,并使用键来查找最常见的 String。存储动物名称。

如果 ArrayList 已排序

[dog, dog, dog, dog, cat, cat, duck, duck]

在不使用Hashmap的情况下查找最常见元素的最简单方法是什么?我正在考虑使用 for 循环将 animalArray.get(i)animalArray.get(i-1) 进行比较,但我无法开发此解决方案。当我们需要查找最常见的元素时,使用排序的 ArrayList 有哪些优点(如果有)?

最佳答案

What is the easiest way to find the most common element without using Hashmaps?

我认为(Java 8+)这非常简单:

String str = list.stream()
                 .distinct()
                 .max(Comparator.comparing(e -> Collections.frequency(list, e)))
                 .get();

这将创建ListStream,并查找List中出现频率最高的元素。

And what are the advantages, if there are any, of having a sorted ArrayList when we need we need to find the most common element?

想象一个未排序的列表:

[dog, cat, turtle, cat, dog, snake]

对于每个元素,您都必须搜索 List 的其余部分以查看它出现的次数。

但是使用排序的列表:

[dog, dog, cat, cat, snake, turtle]

您只需要有一个计数器来跟踪包含相同元素的最长子列表。然后它变成类似(伪代码)的东西:

//T being the type of the List
T element
int count = 0;
int biggestCount = 0;
for(every element in the list) {
   if the item is the same as previous
      count++
   else 
      //Only check when we're about to change elements
      if count > biggestCount
          biggestCount = count
          element = current element of List
      //Starting over with a new element
      count = 1
}
return element

关于java - 在不使用 HashMap 的情况下查找排序的 ArrayList 中最常见的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687379/

相关文章:

linux - 目录名的排序和提取

java - 如何防止 cxf-codegen-plugin 为所有 wsdl 文件生成源

java - 如何使用 Scanner 类使 .next() 在最后打印语句后获取下一个单词?

python - 除以矩阵的向量列

javascript - 在 Javascript 中模拟 map /集合

javascript - html/php 表单转 JSON 的问题

java - 选择排序帮助

java - 为什么 Quartz 说这个 cron 表达式无效?

java - AtomicInteger 是如何工作的?

c - 对数组进行排序会将值替换为零