4
如何編譯第二個方法? 我使用的解決方案謂詞減少Java 8 lambda錯誤:通過減少篩選器集合篩選流THEN map THEN collect
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());
}
}
我不明白你的錯誤。我確實得到了一個未經檢查的任務的警告,因爲您使用原始的Predicate而不是Predicate <? super String>'作爲List List的類型參數。 –