gpt4 book ai didi

Java 8 lambda 错误 : filter stream by reduced filter collection THEN map THEN collect

转载 作者:搜寻专家 更新时间:2023-11-01 03:35:59 24 4
gpt4 key购买 nike

如何编译第二种方法?我使用谓词归约的解决方案

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());
}
}

最佳答案

改变

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

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

为我解决了错误。

关于Java 8 lambda 错误 : filter stream by reduced filter collection THEN map THEN collect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31513770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com