There is a Map<String, List<String>>
. I want to delete a value from the List
if the Map
contains a key.
But is there a way to do it in Java 8 style? Like maybe using compute, merge or some other new method?
The code to remove element from the List in old style way:
public class TestClass {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.put("key1", getList());
map.put("key2", getList());
//remove
if (map.containsKey("key1")) {
map.get("key1").remove("a2");
}
System.out.println(map);
}
public static List<String> getList(){
List<String> arr = new ArrayList<String>();
arr.add("a1");
arr.add("a2");
arr.add("a3");
arr.add("a4");
return arr;
}
}
You could use Map.computeIfPresent()
but the improvement is questionable:
map.computeIfPresent("key1", (k, v) -> { v.remove("a2"); return v; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With