Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write lambda for array inside list

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))...
like image 387
user1298426 Avatar asked Mar 07 '23 07:03

user1298426


2 Answers

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 
like image 65
Eugene Avatar answered Mar 15 '23 09:03

Eugene


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());
like image 26
daniu Avatar answered Mar 15 '23 08:03

daniu