Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 730
Vipul Chauhan Avatar asked Jan 02 '19 16:01

Vipul Chauhan


People also ask

How do you find a specific String in an ArrayList?

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.

How do you find the frequency of an element in an ArrayList?

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.

Can you use a For-Each loop on an ArrayList?

We can use the Java for-each loop to iterate through each element of the arraylist.


1 Answers

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());
like image 107
Ousmane D. Avatar answered Oct 29 '22 03:10

Ousmane D.