I have a Map. The input is coming from another class, so I can't change the format. The value is a List in my case. I want to remove a few elements for a particular key. For example, below is the input map:
Map<String, Object> map = new HashMap<>();
map.put("1", Arrays.asList("A","V","C","M"));
map.put("Roll", 123);
This "map" has been given to me and I want to remove two entries for Key = "1", i.e., Arrays.asList("V","M")
I tried the below code and it worked. I want to know is there any better approach than this. Note: I am trying to do it using Java 8.
List<String> list = Arrays.asList("V","M")
List<String> lst = map.entrySet().stream()
.map(Map.Entry::getValue)
.filter(c -> c instanceof Collection)
.map(c -> (Collection<String>)c)
.flatMap(Collection::stream)
.collect(Collectors.toList());
lst.removeIf(c -> list.contains(c));
/** * After that, I can add this final list to the map again.. */
final output: <"1", {"A", "C"}>
<"Roll", 123>