what to do to compile the second method? I use a predicate reduction solution
predicates.stream().reduce(Predicate::and).orElse(x -> true)
I get this solution from the following topic: How to apply multiple predicates to java.util.Stream?
You know the answer, I'm sure :)
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StreamTest {
@Test
public void should_filter_map_collect__filterByPredicate() {
List<String> strings = Arrays.asList("AA", "AB", "BA", "BB");
Predicate<String> firstCharIsA = s -> s.charAt(0) == 'A';
List<String> l = strings.stream()
.filter(firstCharIsA)
.map(s -> "_" + s + "_")
.collect(Collectors.toList());
}
@Test
public void should_filter_map_collect__filterByReducedPredicates() {
List<String> strings = Arrays.asList("AA", "AB", "BA", "BB");
Predicate<String> firstCharIsA = s -> s.charAt(0) == 'A';
List<Predicate> predicates = new ArrayList<>();
predicates.add(firstCharIsA);
List<String> l = strings.stream()
.filter(predicates.stream().reduce(Predicate::and).orElse(x -> true))
.map(s -> "_" + s + "_")
.collect(Collectors.toList());
}
}
source
share