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.
The contains a () method of the String class accepts Sting value as a parameter, verifies whether the current String object contains the specified string and returns true if it does (else false). Get the array list. Using the for-each loop get each element of the ArrayList object.
Arrays class in Java doesn't have frequency method. But we can use Collections. frequency() to get frequency of an element in an array also.
We can use the Java for-each loop to iterate through each element of the arraylist.
You can do it via a stream as follows:
List<String> result = strings.stream()
.collect(Collectors.groupingBy(Function.identity(), counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 3) // keep only elements that occur 3 times
.map(Map.Entry::getKey)
.collect(Collectors.toList());
You could also do it as follows, but I'd recommend the above as it's more preferable.
List<String> result = new HashSet<>(strings).stream()
.filter(item -> strings.stream()
.filter(e -> e.equals(item)).limit(3).count() == 3)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With