简体   繁体   中英

Java8 Collection Replaceall-Method error

I hope you can help me as I am new to 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". I use the method "replaceAll" to change the single values with the lambda-expression but I get an error.

The error is "incompatible types. Required: 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:

public void replaceAll(UnaryOperator<E> operator)

as you can see it does not return anything, that means it modifies the existing 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM