Vipul Chauhan:
私が持っているArrayList
重複して3回発生する要素を持ついくつかの値が含まれているが、私は特に別に3回発生し、それらの値を収集したいArrayList
など
Arraylist<String> strings; //contains all strings that are duplicates and that occur thrice
ここでは、私は別の配列リストに3回発生するだけで文字列を取得したいです。
Arraylist<String> thrice; //contains only elements that occur three times.
現在、私が持っている解決策重複に対処するために、私は、唯一の3回発生した文字列を取得するために私が見つけるためにこの助けてくださいこれを拡張することはできません。
また:
あなたは両方の質問でacheieveにしようとしているものの一般的なユーティリティが使用されますCollections.frequency
よう:
/**
* @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
再びすべての後の重複を持つことができます。
あるいは、あなたがする方法を使用することができたJava-8の要素の周波数をカウントするエントリ上及び反復Map
所望に応じてフィルタリング処理をそれによって作成され、同じ反復で出力を収集します。
/**
* @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
}