guava - Concatenate Collections with Java 8 -
i want iterate on collection of collections. guava this:
import static com.google.collections.iterables.*; class group { private collection<person> persons; public collection<person> getpersons(); } class person { private string name; public string getname(); } collection<group> groups = ...; iterable<person> persons = concat(transform(groups, group::getpersons())); iterable<string> names = transform(persons, person::getname);
but how can same thing java 8 streams?
groups.stream().map(group::getpersons())...?
you can achieve flat mapping elements of stream stream.
let me explain code:
groups.stream() .flatmap(group -> group.getpersons().stream());
what here, is:
- obtain
stream<collection<group>>
. - then flat map every obtained
stream<person>
,group
, original stream, of typestream<person>
.
now after flatmap()
, can whatever want obtained stream<person>
.
Comments
Post a Comment