I have an object Foo
which contains a list of Bar
. The classes are described as follows:
class Foo {
String name;
List<Bar> bars = new ArrayList<Bar>();
Foo(String name){
this.name = name;
}
}
class Bar {
String name;
Bar(String name){
this.name = name;
}
}
Now, i am creating a list of Foo
objects, each containing a list of Bar
objects as follows:
IntStream
.range(1, 4)
.forEach(i -> foos.add(new Foo("Foo" + i)));
foos.forEach(f ->
IntStream.range(1,4)
.forEach(i -> f.bars.add(new Bar("Bar"+i+" -> "+f.name))));
And then using flatMap
on a Stream
as follows:
foos.stream()
.flatMap(f -> f.bars.stream())
.forEach(i -> System.out.println("Bar Name : "+i.name));
How can do all these things in a single execution using Java Stream
and lambdas? Is there any other way to do such kind of things with Java 8 style?