Views: 274
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
d20160501
Top Tutorials
492.5K
32K
21.8K
18.7K
18.7K
6.7K
6.7K
4.9K
3.3K
3.2K
Top Questions
18.7K
14.5K
8.3K
6.6K
6.2K
5.7K
4.8K
4.8K
4.3K
3.9K
Top Articles
1.9K
1.6K
947
Top Blogs
796
779
55
Top News
754
686
670
398
385
385