Skip to main content

How do I filter elements in a Map

In this Q&A, we'll go over three ways to filter elements in a Map.  Map interface does not expose an iterator or stream method.  We can stream or iterate over Map using Map.entrySet().

Filter using stream

We can stream the Key/Value pairs using entrySet.stream(), filter and eventually create a new filtered Map.  

    public static void filterWithStream() {
        HashMap<Integer, Integer> m = new HashMap<>();
        for( int i =0; i < 10000; ++i)
            m.put(i, i);

        Map<Integer, Integer> m1 = m.entrySet().stream()
                .filter((x) -> x.getKey() > 200 || x.getKey() < 100 )
                .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue));

        System.out.println( m.size() );
        System.out.println( m1.size() );
    }

Filter in-place using iterators

We can also iterate over the Map.entrySet and filter or remove elements in-place using the iterator.

    public static void filterInplacewithIterator() {
        HashMap<Integer, Integer> m = new HashMap<>();
        for( int i =0; i < 10000; ++i)
            m.put(i, i);

        System.out.println( m.size() );

        Iterator<Map.Entry<Integer, Integer>> i = m.entrySet().iterator();
        while( i.hasNext() ) {
            Map.Entry<Integer, Integer> e = i.next();
            if(e.getKey() <= 200 && e.getKey() >= 100 )
                i.remove();
        }
        System.out.println( m.size() );
    }

Filter in-place using removeIf method

The effect of filterInPlaceWithIterator() can be achieved with a single of code instead of a while loop

    public static void filterInplacewithRemove() {
        HashMap<Integer, Integer> m = new HashMap<>();
        for( int i =0; i < 10000; ++i)
            m.put(i, i);

        System.out.println( m.size() );

        m.entrySet().removeIf((x) -> x.getKey()<= 200 && x.getKey() >= 100 );
        System.out.println( m.size() );

    }

Comments