[英]Java8 Collection Replaceall-Method error
I hope you can help me as I am new to Java-8我希望你能帮助我,因为我是 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);
}
}
I have the following problem: I have an ArrayList with 2 Doubles, which I am trying to modify with the method "multi".我有以下问题:我有一个带有 2 个双精度数的 ArrayList,我正在尝试使用“multi”方法对其进行修改。 I use the method "replaceAll" to change the single values with the lambda-expression but I get an error.我使用方法“replaceAll”通过 lambda 表达式更改单个值,但出现错误。
The error is "incompatible types. Required: java.util.List Found: void"错误是“类型不兼容。必需:java.util.List Found:void”
I hope you can help me as I really dont know why I am getting this error.我希望你能帮助我,因为我真的不知道为什么我会收到这个错误。
Let's have a look at the replaceAll method signature:让我们来看看 replaceAll 方法签名:
public void replaceAll(UnaryOperator<E> operator)
as you can see it does not return anything, that means it modifies the existing ArrayList.如您所见,它不返回任何内容,这意味着它修改了现有的 ArrayList。
so in your case, you would need to do something like:因此,在您的情况下,您需要执行以下操作:
public static ArrayList<Double> multi(ArrayList<Double> coll1) {
coll1.replaceAll(aDouble -> aDouble*2.0);
return coll1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.