Removing data from HashMap using removeIf in one line

Views: 163   

Using removeIf we can delete elements of a collection those satisfy given predicate in one liner in Java.

Following sample code shows you how to do that. In the example we are deleting keys that are starting with 'E' from the Hashmap.

package com.reputation.meru.core.util;

import java.util.HashMap;
import java.util.Map;

public class DeleteMe {
    public static void main(String[] args) {
        Map<String, String> employeeIdVsName = new HashMap<>();

        employeeIdVsName.put("E01", "foo");
        employeeIdVsName.put("E02", "bar");
        employeeIdVsName.put("F01", "bar");
        employeeIdVsName.put("F02", "char");
        employeeIdVsName.put("F03", "jar");

        System.out.println(employeeIdVsName);

        employeeIdVsName.keySet().removeIf(key -> key.startsWith("E"));

        System.out.println(employeeIdVsName);
    }
}

Output:

{E02=bar, F01=bar, E01=foo, F03=jar, F02=char}
{F01=bar, F03=jar, F02=char}
On By