Get the Strings that occur exactly three times from Arraylist<String>

  • A+

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             .filter(a -> Collections.frequency(input, a) == n) // filter by number of occurrences             .collect(Collectors.toSet()); // collecting to a final set (one representation of each) } 

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.

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 // 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 } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: