【问题标题】:Java8 Collection Replaceall-Method errorJava8 Collection Replaceall-Method 错误
【发布时间】:2016-04-24 17:51:04
【问题描述】:

我希望你能帮助我,因为我是 Java-8 的新手

public class main {

    public static void main(String[] args){
        ArrayList<Double> coll1 = new ArrayList<>();
        coll1.add(2.5);
        coll1.add(3.5);
        printColl(multi(coll1));
    }

    public static ArrayList<Double> multi(ArrayList<Double> coll1) {
        return coll1.replaceAll(aDouble -> aDouble*2.0);
    }

    public static void printColl(ArrayList<?> coll) {
        coll.stream().forEach(System.out::println);
    }
}

我有以下问题:我有一个带有 2 个 Doubles 的 ArrayList,我正在尝试使用“multi”方法对其进行修改。我使用“replaceAll”方法通过 lambda 表达式更改单个值,但出现错误。

错误是“不兼容的类型。必需:java.util.List Found: void”

希望您能帮助我,因为我真的不知道为什么会出现此错误。

【问题讨论】:

标签: java collections java-8


【解决方案1】:

我们看一下replaceAll方法签名:

public void replaceAll(UnaryOperator&lt;E&gt; operator)

如您所见,它不返回任何内容,这意味着它修改了现有的 ArrayList。

所以在您的情况下,您需要执行以下操作:

public static ArrayList<Double> multi(ArrayList<Double> coll1) {
        coll1.replaceAll(aDouble -> aDouble*2.0);
        return coll1;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 2020-10-25
    • 1970-01-01
    • 2013-09-03
    • 2016-02-09
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多