sakirow
sakirow

Reputation: 229

how to find an element in array of object with streams

I have object list.

List<Item> itemList = new ArrayList<>();

every Item has 1 arrayList

public class Item {
    private String id;
    private List<Property> propertyList;
}

Property has key and value as String

public class Property {
    private String key;
    private String value;
}

I want to create a stream on Itemlist and get the new list which contains

Item.propertyList.key.equals("Test") as a new list.

Upvotes: 0

Views: 3867

Answers (3)

Joel Neukom
Joel Neukom

Reputation: 639

If you want to have a list of matching Property classes, you can do it with flatMap:

final List<Property> collect = itemList.stream()
            .flatMap(item -> item.getPropertyList().stream())
            .filter(property -> "Test".equals(property.getKey()))
            .collect(Collectors.toList());

Upvotes: 1

Michael
Michael

Reputation: 44110

Bit cleaner than Hadi's suggestion:

itemList.stream()
   .filter(item -> item.getPropertyList()
          .stream().map(Property::getKey).anyMatch("Test"::equals))
   .collect(Collectors.toList());

Upvotes: 4

Hadi
Hadi

Reputation: 17289

You can do like this:

itemList.stream()
          .filter(item -> item.getPropertyList()
                         .stream().anyMatch(property -> property.getKey().equals("Test")))
           .collect(Collectors.toList());

Upvotes: 3

Related Questions