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

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -