Friday, 15 January 2010

Java 8 map merge method -



Java 8 map merge method -

i trying create hashmap contain integer key , list of strings value:

map<integer, list<string>> map = new hashmap<integer, list<string>>(30);

i want somehow populate efficiently. came was:

map.merge(search_key, new arraylist<>(arrays.aslist(new_string)), (v1, v2) -> { v1.addall(v2); homecoming v1; });

this code little , elegant problem create new list in every call. there way can skip list creation after first merge, , add together new_string in first created list?

you should utilize method map::computeifabsent create list lazily:

map.computeifabsent(search_key, k -> new arraylist<>()) .add(new_string);

java map merge java-8

No comments:

Post a Comment