collect a synchronized arraylist from streams in java 8 -
list<string> result = map.entryset() .stream() .map(map.entry::getvalue) .flatmap(x -> x.stream()) .collect(collectors.tocollection(arraylist::new)); the above code create arraylist not thread safe. how can make thread safe.
if want synchronized collection, can change collector provide implementation want, example:
.collect(collectors.tocollection(() -> collections.synchronizedlist(new arraylist<> ())); or if prefer concurrent collection:
.collect(collectors.tocollection(copyonwritearraylist::new)); in latter case, may more efficient use copy constructor avoid unnecessary copies of underlying array.
Comments
Post a Comment