public class FlatMapTest {
public List<List<Person>> f() {
List<List<Person>> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
List<Person> listPerson = new ArrayList<>();
for (int j = 0; j < 3; j++) {
Person p = new Person();
p.name = "" + i * j;
listPerson.add(p);
}
list.add(listPerson);
}
return list;
}
public static void main(String[] args) {
FlatMapTest fmt = new FlatMapTest();
List<List<Person>> l = fmt.f();
List<String> strings = l.stream().flatMap(x -> Arrays.stream(x.toArray(new Person[x.size()]))).map(x -> x.name).collect(Collectors.toList());
System.out.println(strings);
}
class Person{
String name;
String sex;
int age;
}
}
flatMap用来解除两层嵌套。就是书上说的把流扁平化。