Java 8 — Unary Operator | Code Factory

Code Factory
2 min readMay 7, 2020

--

Index Page : Link

Reference Link : Link

Donate : Link

  • If input and output are same type then we should go for UnaryOperator
  • It is child of Function<T, T>

Demo Program to find square of given integer by using Function :

package com.codeFactory.unaryOperator;import java.util.function.Function;public class Test {
public static void main(String... args) {
Function<Integer, Integer> f = i -> i * i;
System.out.println(f.apply(3));
}
}

Output :

9

Demo Program to find square of given integer by using UnaryOperator :

package com.codeFactory.unaryOperator;import java.util.function.UnaryOperator;public class Test {
public static void main(String... args) {
UnaryOperator<Integer> f = i -> i * i;
System.out.println(f.apply(3));
}
}

Output :

9

The primitive versions for UnaryOperator :

1. IntUnaryOperator

@FunctionalInterface
public interface IntUnaryOperator {
int applyAsInt(int operand);
default IntUnaryOperator compose(IntUnaryOperator before) { }
default IntUnaryOperator andThen(IntUnaryOperator after) { }
static IntUnaryOperator identity() { }
}

2. LongUnaryOperator

@FunctionalInterface
public interface LongUnaryOperator {
long applyAsLong(long operand);
default LongUnaryOperator compose(LongUnaryOperator before) { }
default LongUnaryOperator andThen(LongUnaryOperator after) { }
static LongUnaryOperator identity() { }
}

3. DoubleUnaryOperator

@FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
default DoubleUnaryOperator compose(DoubleUnaryOperator before) { }
default DoubleUnaryOperator andThen(DoubleUnaryOperator after) { }
static DoubleUnaryOperator identity() { }
}

Example 1 :

package com.codeFactory.unaryOperator;import java.util.function.IntUnaryOperator;public class Test {
public static void main(String... args) {
IntUnaryOperator u = i -> i * i;
System.out.println(u.applyAsInt(3));
}
}

Output :

9

Example 2 :

package com.codeFactory.unaryOperator;import java.util.function.IntUnaryOperator;public class Test {
public static void main(String... args) {
IntUnaryOperator u1 = i -> i + i;
System.out.println(u1.applyAsInt(3));

IntUnaryOperator u2 = i -> i * i;
System.out.println(u2.applyAsInt(3));

System.out.println(u1.andThen(u2).applyAsInt(3));
}
}

Output :

6
9
36

--

--

No responses yet