Vector replaceAll(UnaryOperator) in Java

replaceAll(UnaryOperator): This method is available in java.util.Vector class of Java.

Syntax:

void java.util.Vector.replaceAll(UnaryOperator<K> operator)

This method takes one argument. This method replaces each element of this list with the result of applying the operator to that element.

Parameters: One parameter is required for this method.

operator: the operator to apply to each element.

Returns: NA

Throws:

NullPointerException - if the specified operator is null or if the operator result is a null value and this list does not permit null elements.

Approach 1: When no exception

Java

import java.util.Vector;
import java.util.function.UnaryOperator;

public class VectorreplaceAll {
    public static void main(String[] args) {

        Vector<Integer> vector = new Vector<>();

        vector.add(5);
        vector.add(4);
        vector.add(12);
        vector.add(6);

        UnaryOperator<Integer> operator = k -> k - 1;
        vector.replaceAll(operator);

        System.out.println(vector);
    }
}

Output:

[4, 3, 11, 5]


Approach 2: NullPointerException 

Java

import java.util.Vector;
import java.util.function.UnaryOperator;

public class VectorreplaceAll {
    public static void main(String[] args) {

        Vector<Integer> vector = new Vector<>();

        vector.add(5);
        vector.add(4);
        vector.add(12);
        vector.add(6);

        UnaryOperator<Integer> operator = null;
        vector.replaceAll(operator);

        System.out.println(vector);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Vector.replaceAll(Vector.java:1369)


No comments:

Post a Comment