For Ex:
A = {1,2,2,3,4,4,4,5,5,5,5,5}
Output: {1,2,5}
1 is occured 1's
2 is occured twice
3 does not occcured thrice
and so on.
I have tried to create the hashmap of occurences. But not sure how to continue the stream and return values which satisfy condition i.e {1,2,5}
List<Integer> words = Arrays.asList(1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5, 5);
System.out.println(frequencyMap(words.stream()));
public static <Integer > Map < Integer, Integer > frequencyMap(Stream < Integer > elements) {
return (Map<Integer, Integer>) elements.collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
}
If I understand your problem, you need to use filter
like this:
List<Integer> result = words.stream()
.collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1)))
.entrySet().stream()
.filter(entry -> entry.getKey().equals(entry.getValue()))
.map(Map.Entry::getKey)
.toList();