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

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

I already got A object from stream as shown below but can't find way to complete this lambda to get List of ids which is inside B class.

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

2 Answers 2

5

You are looking for flatMap here:

 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 
Sign up to request clarification or add additional context in comments.

Comments

2

You need to use flatMap:

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

Now it's a Stream<B>; you can map that to their Ids now

    .map(B::getId)

and make a list out of this.

    .collect(Collectors.toList());

2 Comments

The OP wants a List with B's Id List<String> bId lines.map(x -> (A)gson.fromJson(x, type)).flatMap(a -> Arrays.stream(a.getB()).map(B::getId).collect(Collectors.toList());
@DavidPérezCabrera You're right. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.