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>
There is no need of stream for doing this, i prefer using computeIfPresent
if key present in Map
alter the value else ignore. Don't use Arrays.asList unless you need immutable list because it will not support remove
operation
List<String> list = new ArrayList<String>();
list.add("A");
list.add("V");
list.add("C");
list.add("M");
Map<String, Object> map = new HashMap<>();
map.put("1", list);
map.put("Roll", 123);
List<String> remove = Arrays.asList("V","M");
map.computeIfPresent("1", (k,v)->{
if(Objects.nonNull(v) && v instanceof List) {
@SuppressWarnings("unchecked")
List<String> result = (List<String>) v;
result.removeIf(i->remove.contains(i));
return result;
}
return v;
});
System.out.println(map); //{1=[A, C], Roll=123}