Karan Verma Karan Verma - 9 days ago 6
Java Question

Java 8 FlatMap - Add items in a nested form and retrieve object using FlatMap

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?

Answer

If all you’re going to do, is to print the names of the Bar instances, the entire construction and collection of Foo and Bar instances is obsolete. You can generate and print the names directly:

IntStream.range(1, 4)
         .mapToObj(i -> "Foo" + i)
         .flatMap(name -> IntStream.range(1, 4)
            .mapToObj(i -> "Bar" + i + "->" + name))
         .forEach(System.out::println);