1

I am trying to access a list of string from a data structure which is having collection of collection. What I have tried yet is returning a list of collection,but I want a single list. Here is my code:

    Collection result= (Collection)allPatientsAccessRecords.stream()
            .filter(rec -> rec.data.personId==8191).map(data->data.accessData.associatedAreas).
                    collect(Collectors.toList());

Here is a snapshot of a source data structure: enter image description here

Can someone hint me how i can get accessData->associatedArea(list of string) as a result using stream API ?

Raja Jawahar
  • 6,742
  • 9
  • 45
  • 56
user565
  • 871
  • 1
  • 22
  • 47
  • Possible duplicate of [What's the difference between map and flatMap methods in Java 8?](https://stackoverflow.com/questions/26684562/whats-the-difference-between-map-and-flatmap-methods-in-java-8) – Hulk Jun 05 '18 at 12:22

2 Answers2

3

Use flatMap

allPatientsAccessRecords.stream()
        .filter(rec -> rec.data.personId == 8191)
        .flatMap(data -> data.accessData.associatedAreas.stream())
        .collect(Collectors.toList());
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
1

This should get you started:

List<List<String>> example = ... ;
example.stream().flatMap(list->list.stream()).collect(...)
Michal
  • 970
  • 7
  • 11