I have a Collection<Product>
and a Collection<Predicate<Product>>
. The Predicates are a simple combination of boolean flags. For example:
| isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true | false
predicate 4: | true | true
I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.
Currently my code looks like this:
List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();
List<Product> result = predicates.stream()
.flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
.collect(Collectors.toList());
But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.
In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst
this Predicate then can be skipped for all other Products.
I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.