Ish
Ish

Reputation: 4154

Java 8 Nested Streams Filtering

Here are my classes:

class File {
  String id;
  String name;
  List<Metadata> metadata;
}

class Metadata {
  String key;
  String value;
}

I have a list of files (List<File>), I wanted to filter first by the name of the File, and then filter by the matching key and value from the list of Metadata.

Let's say, I wanted to return the id of the File which name is "movie.mp4" and one of its metadata should have key=="genre" and value=="Horror".

Using Java 8 Streams, I can filter by the name of File, but not sure how to go down another level and filter by the matching key and value.

How do I do this?

Upvotes: 2

Views: 108

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201439

Call stream() on the metadata and test if any key and value match your criteria. Something like,

fileList.stream().filter(f -> f.name.equals("movie.mp4")
        && f.metadata.stream().anyMatch(x -> x.key.equals("genre")
        && x.value.equals("Horror")));

Upvotes: 2

Related Questions