Java 8 lambda error: filter stream using a reduced filter collection. THEN map THEN collect

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 {
    /**
     * This one works
     */
    @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());
    }

    /**
     * Compilation Error:(43, 25) java: incompatible types: java.lang.Object cannot be converted to java.util.List<java.lang.String>
     */
    @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());
    }
}
+4
source share
1 answer

Change

List<Predicate> predicates = new ArrayList<>();

to

List<Predicate<String>> predicates = new ArrayList<>();

solved the error for me.

+1
source

Source: https://habr.com/ru/post/1598674/


All Articles