从Arraylist< String>中获取恰好发生三遍的字符串. [英] Get the Strings that occur exactly three times from Arraylist<String>
问题描述
我有一个ArrayList
,其中包含一些具有重复项和三次出现的值的值,我想将那些三次发生的值专门收集到另一个ArrayList
中,例如
I have an ArrayList
which contains some values with duplicates and elements that occur thrice, I want to collect those values that occur thrice specifically into another ArrayList
like
Arraylist<String> strings; //contains all strings that are duplicates and that occur thrice
在这里,我只想获取在另一个数组列表中三次出现的字符串.
Here, I want to get only the Strings that occur thrice in another array list.
Arraylist<String> thrice; //contains only elements that occur three times.
Currently, I have a solution for dealing with duplicates but I cannot extend this for only getting strings that occur thrice, this please help me to find out.
推荐答案
A generic utility of what you're trying to acheieve in both the questions would be using Collections.frequency
as :
/**
* @param input the list as your input
* @param n number of occurrence (duplicates:2 , triplets:3 etc..)
* @param <T> (type of elements)
* @return elements with such conditional occurrent in a Set
*/
static <T> Set<T> findElementsWithNOccurrence(List<T> input, int n) {
return input.stream()
.filter(a -> Collections.frequency(input, a) == n) // filter by number of occurrences
.collect(Collectors.toSet()); // collecting to a final set (one representation of each)
}
注意 :这将是一种 O(n^2)
方法,因为它使用了Collections.frequency
,该方法再次遍历整个集合以获取频率.但建议针对您要的内容采用一种更具可读性和通用性的方法.另外,这有意将最终输出收集到Set
,因为List
毕竟可以再次具有重复项.
Note: This would be an O(n^2)
approach since its using Collections.frequency
which iterates over the entire collection again to get the frequency. But proposed for a more readable and generic approach towards what you're looking for. Also, this intentionally collects final output to a Set
, since a List
can again have duplicates after all.
或者,您可以使用该方法计算Java-8中元素的频率,然后遍历创建的Map
可以根据需要进行过滤,并在同一迭代中收集输出:
Alternatively, you can use the method to count the frequency of elements in Java-8 and iterate over the entries of the Map
created thereby to process filtering as desired and collect the output in the same iteration :
/**
* @param input the list as your input
* @param n number of occurrence (duplicates :2 , triplets :3 etc)
* @param <T> (type of elements)
* @return elements in a set
*/
static <T> Set<T> findElementsWithNOccurrence(List<T> input, int n) {
return input.stream() // Stream<T>
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting())) // Map<T, Long>
.entrySet() // Set<Map.Entry<T,Long>>
.stream() // Stream<Map.Entry<T,Long>>
.filter(e -> e.getValue() == n) // filtered with frequency 'n'
.map(Map.Entry::getKey) // Stream<T>
.collect(Collectors.toSet()); // collect to Set
}
这篇关于从Arraylist< String>中获取恰好发生三遍的字符串.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!