Custom UnaryOperator implementation in java.

JavaObject Oriented ProgrammingProgramming

The java.util.function.UnaryOperator interface and can be used as assignment target for lambda expressions, it represents operation on a single operand whose result will be of same type as the input. We can create our own UnaryOperator by implementing this interface.

The replaceAll() method of the List interface accept an object of the UnaryOperator representing a particular operation performs the specified operation on all the elements of the current list and replaces the existing values with the resultant values.

In the following example we are implementing the UnaryOperator interface and creating a custom unary operator object and trying to pass it as an argument to the replaceAll() method.

Example

 Live Demo

import java.util.ArrayList;
import java.util.function.UnaryOperator;
class Op implements UnaryOperator<String> {
   public String apply(String str) {
      return str.toUpperCase();
   }
}
public class Test {
   public static void main(String[] args) throws CloneNotSupportedException {
      ArrayList<String> list = new ArrayList<>();
      list.add("Java");
      list.add("JavaScript");
      list.add("CoffeeScript");
      list.add("HBase");
      list.add("OpenNLP");
      System.out.println("Contents of the list: "+list);
      list.replaceAll(new Op());
      System.out.println("Contents of the list after replace operation: \n"+list);
   }
}

Output

Contents of the list: [Java, JavaScript, CoffeeScript, HBase, OpenNLP]
Contents of the list after replace operation:
[JAVA, JAVASCRIPT, COFFEESCRIPT, HBASE, OPENNLP]
raja
Published on 10-Jan-2020 10:31:14
Advertisements