Get the Strings that occur exactly three times from Arraylist<String>
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());
Basically, instead of using a HashSet you now want to use a HashMap to count the number of occurrences of each string.
Furthermore, instead of writing a method for finding the strings that occur three times specifically, you could write a method that takes in a parameter, n
and finds the strings that occur N times:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
class StackOverflowQ {
static List<String> getStringsThatOccurNTimes(List<String> stringList, int n) {
if (stringList == null || stringList.size() == 0) {
return stringList;
}
Set<String> stringsThatOccurNTimesSet = new HashSet<>();
Map<String, Integer> stringCounts = new HashMap<>();
for (String s : stringList) {
int currentStringCount = stringCounts.getOrDefault(s, 0) + 1;
stringCounts.put(s, currentStringCount);
if (currentStringCount == n) {
stringsThatOccurNTimesSet.add(s);
} else if (currentStringCount == n + 1) {
stringsThatOccurNTimesSet.remove(s); // We use a set so this operation is O(1)
}
}
return new ArrayList<>(stringsThatOccurNTimesSet);
}
public static void main(String[] args) {
List<String> stringsList = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "b", "c", "c", "d", "d", "d", "e"));
List<String> stringsThatOccurTwoTimes = getStringsThatOccurNTimes(stringsList, 2);
List<String> stringsThatOccurThreeTimes = getStringsThatOccurNTimes(stringsList, 3);
List<String> stringsThatOccurFourTimes = getStringsThatOccurNTimes(stringsList, 4);
System.out.println("Original list: " + stringsList);
System.out.println("Strings that occur two times: " + stringsThatOccurTwoTimes);
System.out.println("Strings that occur three times: " + stringsThatOccurThreeTimes);
System.out.println("Strings that occur four times: " + stringsThatOccurFourTimes);
}
}
Output:
Original list: [a, b, c, d, e, b, c, c, d, d, d, e]
Strings that occur two times: [b, e]
Strings that occur three times: [c]
Strings that occur four times: [d]