Search code examples
javajava-8java-stream

Write a program using streams - Get the elements which whose occurence is not equal to it's value


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()));
}

Solution

  • 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();
    
    1. Count occurrences: counts how many times each number appears in the list (words).
    2. Filter by count: Keeps only the numbers that appear the same number of times as their value.