如何编译第二种方法?
我使用解决方案来减少谓词
predicates.stream().reduce(Predicate::and).orElse(x -> true)
你知道答案,我确定:)
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 strings = Arrays.asList("AA", "AB", "BA", "BB");
Predicate firstCharIsA = s -> s.charAt(0) == 'A';
List 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
*/
@Test
public void should_filter_map_collect__filterByReducedPredicates() {
List strings = Arrays.asList("AA", "AB", "BA", "BB");
Predicate firstCharIsA = s -> s.charAt(0) == 'A';
List predicates = new ArrayList<>();
predicates.add(firstCharIsA);
List l = strings.stream()
.filter(predicates.stream().reduce(Predicate::and).orElse(x -> true))
.map(s -> "_" + s + "_")
.collect(Collectors.toList());
}
}