November 21, 2020

Use IntUnaryOperator to calculate sum and cube of an int using modern java : java functional programming

There are different ways to implement IntUnaryOperator .

You can watch my video, where I am implementing IntUnaryOperator.

Utility Class with square and cube static functions.

private static class Utility{
    private static final int square(final int intValue) { return (int) intValue * intValue; }
    private static final int cube(final int intValue) { return (int) intValue * intValue * intValue; }
}

Implementation to calculate square.

Regular Class Implementation

private static class Square implements IntUnaryOperator{
        @Override
    public int applyAsInt(final int intValue){ return intValue * intValue; }
    }

Anonymous Class

private static final IntUnaryOperator squareAnonClass =  new IntUnaryOperator(){
    @Override
    public int applyAsInt(final int intValue){ return intValue * intValue; }
};

Lambda Full Implementation

private static final IntUnaryOperator squareImpl   = (int intValue) -> intValue * intValue;

Lambda Short Implementation

private static final IntUnaryOperator squareImpl_2 = intValue -> intValue * intValue;

Method Reference Implementation

private static final IntUnaryOperator squareImpl_3 = Utility::square;

Cube Implementation

Regular Class

private static class Cube implements IntUnaryOperator{
    @Override
public int applyAsInt(final int intValue) { return intValue * intValue * intValue; }
}

Anonymous Class

private static final IntUnaryOperator cubeAnonClass = new IntUnaryOperator(){
    @Override
public int applyAsInt(final int intValue) { return intValue * intValue * intValue; }
};

Lambda Full Implementation

private static final IntUnaryOperator cubeImpl   = (int intValue) -> intValue * intValue * intValue;

Lamdba Short Implementation

private static final IntUnaryOperator cubeImpl_2 = intValue -> intValue * intValue * intValue;

Lambda Method Reference Implementation

private static final IntUnaryOperator cubeImpl_3 = Utility::cube;

You can find full source code here.