How to write lambda for an array inside a list

public class A
{
    private B[] b;
    //getter setter
}

public class B
{
    private String id;
    //getter setter
}

I already got the object from the stream, as shown below, but I can not find a way to complete this lambda to get a list of identifiers, which is inside class B.

Stream <String> lines = Files.lines(Paths.get("file.json"));
lines.map(x -> (A)gson.fromJson(x, type))...
+4
source share
2 answers

You are looking flatMaphere:

 lines.map(x -> (A)gson.fromJson(x, type))
      .flatMap(y -> Arrays.stream(y.getB()))
      .map(B::getId)
      .collect(Collectors.toSet())  // or any other terminal operation 
+5
source

You need to use flatMap:

 lines.map(x -> (A)gson.fromJson(x, type)).flatMap(a -> Arrays.stream(a.getB())

Now this is a Stream<B>; you can match this with their ids now

    .map(B::getId)

and make a list of it.

    .collect(Collectors.toList());
+2
source

Source: https://habr.com/ru/post/1691221/


All Articles