Java 8 — Unary Operator | Code Factory

  • If input and output are same type then we should go for UnaryOperator
  • It is child of Function<T, T>
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));
}
}
9
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));
}
}
9

The primitive versions for UnaryOperator :

@FunctionalInterface
public interface IntUnaryOperator {
int applyAsInt(int operand);
default IntUnaryOperator compose(IntUnaryOperator before) { }
default IntUnaryOperator andThen(IntUnaryOperator after) { }
static IntUnaryOperator identity() { }
}
@FunctionalInterface
public interface LongUnaryOperator {
long applyAsLong(long operand);
default LongUnaryOperator compose(LongUnaryOperator before) { }
default LongUnaryOperator andThen(LongUnaryOperator after) { }
static LongUnaryOperator identity() { }
}
@FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
default DoubleUnaryOperator compose(DoubleUnaryOperator before) { }
default DoubleUnaryOperator andThen(DoubleUnaryOperator after) { }
static DoubleUnaryOperator identity() { }
}
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));
}
}
9
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));
}
}
6
9
36

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Deploy Your Front End App To Netlify in less than 5 minutes

All-Time Highs Coming for Cardano!!!

👉 By joining to the given Telegram channels and groups, as well as following our Twitter page, you…

iOS Image-Processing Architecture Diagrams

Five Steps for a Successful Salesforce Implementation

Do we need another chip to generate DTMF tones with Arduino?

Intercepting incoming request using Spring’s Interceptor

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
Code Factory

Code Factory

More from Medium

Functional Interfaces in Java

Java vs C sharp: Top 8 Important Differences To Know

Singleton Design Pattern in Java

Comparison Inheritance And Polymorphism in JAVA