如何编译第二种方法? 我使用解决方案来减少谓词
predicates.stream().reduce(Predicate::and).orElse(x -> true)
我从以下主题获得此解决方案:How to apply multiple predicates to a java.util.Stream?
你知道答案,我确定:)
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());
}
}
答案 0 :(得分:1)
更改
List<Predicate> predicates = new ArrayList<>();
到
List<Predicate<String>> predicates = new ArrayList<>();
为我解决了错误。