![](/img/trans.png)
[英]find the most and least used string in an ArrayList (without using Hashmap)
[英]Finding the most frequent String in a sorted ArrayList without using HashMap
考虑String
的ArrayList
包含
animalsArray[dog, cat, dog, dog, cat, duck, duck, dog]
我可以轻松地使用HashMap
来查找最常见的String
,使用HashMap
值作为计数器,以及存储动物名称的键。
如果ArrayList
已排序
[dog, dog, dog, dog, cat, cat, duck, duck]
不使用Hashmaps
查找最常见元素的最简单方法是什么? 我当时正在考虑使用for循环将animalArray.get(i)
与animalArray.get(i-1)
但是我无法开发此解决方案。 如果需要,拥有排序的ArrayList
有什么好处(如果有),我们需要找到最常见的元素?
不使用哈希图查找最常见元素的最简单方法是什么?
我认为(Java 8+)这很容易:
String str = list.stream()
.distinct()
.max(Comparator.comparing(e -> Collections.frequency(list, e)))
.get();
这将创造一个Stream
中的List
,并找到在最频率的元素List
。
如果需要,拥有排序的ArrayList有什么好处(如果有),我们需要找到最常见的元素?
想象一个未排序的List
:
[dog, cat, turtle, cat, dog, snake]
对于每个元素,您都必须搜索List
的其余部分,以查看它出现了多少次。
但是与排序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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.