vendredi 17 juin 2016

Stream and filter for structure of Lists

Trying to get list of items from structure and avoid lot of for cycles and ifs, so I wanna use Stream

For example, lets have a following structure:

class House {
List<Family> familyList;
}

class Family {
List<Person> personList;
String someInfo;

}

class Person {
String name;
int age;
List<Item> itemList;
}

class Item{
String name;    
}

I want to create: 1.List<Item> from families
2.List<Item> from families filtered by name
3.List<Family> from house, which contain only records filtered by item name

so far I tried : 1:

List<Item> testItems = house1.familyList.stream().flatMap(f -> f.personList.stream().flatMap(p ->p.itemList.stream()))
    .collect(Collectors.toList());
List<Item> testItems = house1.familyList.stream().flatMap(f -> f.personList.stream()).flatMap(p->p.itemList.stream())
                .collect(Collectors.toList());

2:

List<Item> testItemsFiltered= house1.familyList.stream().flatMap(f -> f.personList.stream().flatMap(p ->p.itemList.stream().filter(item->item.name.equals("Hammer"))))
    .collect(Collectors.toList());

but both are throwing nullpointers

for 3. variant I have no idea so far

Aucun commentaire:

Enregistrer un commentaire