ArrayListのから正確に3回発生し、その文字列を取得します。<文字列>

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
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=173863&siteId=1
おすすめ