Java 8 — Unary Operator | Code Factory

Index Page : Link

Reference Link : Link

Donate : Link

  • If input and output are same type then we should go for UnaryOperator

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store