Skip to main content

Posts

Featured post

Java 8 - Optional - Or Else Throw

orElseThrow operation throws an exception in cases where the optional is empty.The exception is obtained from a Supplier function.

@Slf4j
public class OrElseThrow {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   @SneakyThrows
   public static void main(String[] args) {
     log.info("orElseThrow on optional throws an exception if optional is empty");

     acquaintance_1.orElseThrow(() -> new Exception("value not present"));
   }
}
Recent posts

Java 8 - Optional - Or Else Get

orElseGet operation provides a fallback value in cases where the optional is empty.The fallback value is obtained from a supplier function.

@Slf4j
public class OrElseGet {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("orElseGet on optional provides a fallback: " + acquaintance_1.orElseGet(() -> new Person("Tom", "Cruise")) );
   }
}

Java 8 - Optional - Or Else

orElse operation provides a fallback value in cases where the optional is empty.

@Slf4j
public class OrElse {

   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("orElse on optional provides a fallback: " + acquaintance_1.orElse(new Person("Tom", "Cruise")) );
   }
}

Java 8 - Optional - Map

map operation on an optional returns a transformation of the optional.This transformation does not mutate the original optional.

@Slf4j
public class Map {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

   @RequiredArgsConstructor
   @ToString
   class Mammal {
     final String firstName;
     final String lastName;
   }

   log.info("transforming optional of person to optional of mammal: " + dj.map(person -> new Mammal(person.getFirstName(), person.getLastName())) );

   log.info("map on optional does not mutate original optional: " + dj.get().getFirstName().equals("DJ") );

   }
}

Java 8 - Optional - Is Present

isPresent operation on an optional returns a boolean indicating whether or not the optional has a value.

@Slf4j
public class IsPresent {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));
   static Optional<Person> acquaintance_1 = Optional.ofNullable(null);

   public static void main(String[] args) {

     log.info("isPresent on an optional returns true if there's a value: " + dj.isPresent() );

     log.info("isPresent on an optional returns false if there's no value: " + acquaintance_1.isPresent() );

   }
}

Java 8 - Optional - If Present

ifPresent operation on an optional applies a Consumer function to the value of the optional. If the optional is empty, nothing happens.

@Slf4j
public class IfPresent {

   static Optional dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("ifPresent on an optional applies the consumer function");

     dj.ifPresent(person -> log.info(person.toString()));
   }
}

Java 8 - Optional - Get

get operation on an optional returns the value of the optional.If the optional is empty, exception is thrown.

@Slf4j
public class Get {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));
   static Optional<Person> usher_2 = Optional.empty();

   public static void main(String[] args) {

     log.info("get on an optional returns the value: " + dj.get() );

     log.info("get on an empty optional throws exception:");
     usher_2.get();
   }
}

Java 8 - Optional - Flat Map

When a transformation on an optional transforms such optional to an optional of optional, we use flatMap to flatten the result back to an optional.
@Slf4j
public class FlatMap {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("flatMap on an option flattens the result to an optional value: " +

      dj.flatMap(person -> {

       if(person.getFirstName().equals("Paul"))
        return Optional.of(new Person("DJ_2", "JimmyJack"));

       return dj;
     })
    );

   }
}

Java 8 - Optional - Filter

Filter operation on an optional returns an optional if the predicate function is satisfied, otherwise it returns empty.
@Slf4j
public class Filter {

   static Optional<Person> dj = Optional.of(new Person("DJ", "JimmyJack"));

   public static void main(String[] args) {

     log.info("filter on an option returns an empty optional if predicate is not satisfied: " + dj.filter(person -> person.getFirstName().equals("Paul")) );

     log.info("filter on an option returns an optional if predicate is satisfied: " + dj.filter(person -> person.getFirstName().equals("DJ")) );
   }
}

Java 8 - Optional - Introduction

The optional data type is useful for representing an object which can have a null value.It prevents null pointer exceptions and also provides useful operations on the object.
public abstract class IntroductionToOptionals {

   /*
    * let's assume we are having a party, and the party could have a DJ, MC and Usher
    * It's best to represent them as optional as their presence at the party is really optional
   * */
   Optional dj = Optional.of(new Person("DJ", "JimmyJack"));
   Optional mc = Optional.of(new Person("MC", "Hammer"));
   Optional usher = Optional.of(new Person("Usher", "Ray"));

   /*
    * assuming there could be a second Usher who we can bet won't attend, we can set such
    * usher to an empty option
   */
   Optional usher_2 = Optional.empty();

   /*
    * assuming also that two acquaintances may attend the party, but we c…

Java 8 - Functions - Function Types - Supplier

A Supplier is a function which returns an output without any input.
@Slf4j
public class Supplier_ {

    static Supplier<Person> personSupplier = () -> new Person("Tom", "Smith");

    public static void main(String[] args) {
      log.info("supplied person is " + personSupplier.get());
    }

}

Java 8 - Functions - Function Types - Predicate

A Predicate is a function which acts on an input to return a boolean.A Predicate can be transformed to its negated value using negatePredicates can be composed using and and or.
@Slf4j
public class Predicate_ {

   static Function<String, Boolean> normalPredicateFunc = s -> s.length() > 0;
   static Predicate<String> nonEmptyString = s -> s.length() > 0;

   static Predicate<String> emptyString = nonEmptyString.negate();

   static Predicate<String> correctLength = nonEmptyString.and(s -> s.length() > 2);
   static Predicate<String> validString = correctLength.or(nonEmptyString);

   public static void main(String[] args) {
     log.info("predicates match: " + (nonEmptyString.test("hi") == normalPredicateFunc.apply("hi")));

     log.info("string is empty: " + emptyString.test(""));

     log.info("string is valid: "…

Java 8 - Functions - Function Types - Identity Function

An Identity function is a function which returns it's input as output.

@Slf4j
public class IdentityFunction {

   static Function<Integer, Integer> identifyFunc = x -> x;
   static Function<Integer, Integer> identifyFunc2 = Function.identity();
   static Function<Integer, Integer> identifyFunc3 = UnaryOperator.identity();

   public static void main(String[] args) {
     log.info("identify function input matches output: " + (identifyFunc.apply(1) == 1));
     log.info("second identify function input matches output: " + (identifyFunc2.apply(2) == 2));
     log.info("third identity function input matches output: " + (identifyFunc3.apply(3) == 3));
   }
}


Java 8 - Functions - Function Types - Primitive Args Functions

There are cases when the performance cost of auto boxing is significant.When dealing with a lot of primitive values, avoid auto boxing by creating lambdas that use primitives.The examples shown below use int primitive type, but there are corresponding versions for the double and long primitive types, just replace Int with Double or Long.
@Slf4j
public class FunctionsWithPrimitiveArgs {

    /*
     function to convert int to any type
    */
    IntFunction<String> intToString = i -> Integer.toString(i);

    /*
     function to convert any type to int
    */
    ToIntFunction<String> parseInt = str -> Integer.valueOf(str);

    /*
     function that takes an int to return a boolean i.e a Predicate accepting int input
    */
    IntPredicate isEven = i -> i % 2 == 0;

    /*
     function that takes two inputs to return an int
    */
    ToIntBiFunction<String,String> maxLength = (left, right…

Java 8 - Functions - Function Types - Function

A Function acts on an input and returns an output.A UnaryOperator is a function whose input and output are of the same type.A BiFunction is a function which acts on two inputs and returns an output.A BinaryOperator is a BiFunction whose input and output are of the same type.BinaryOperator.minBy and BinaryOperator.maxBy return a BinaryOperator which calculate min and max values of two inputs.
@Slf4j
public class Function_ {

   static Function<Integer, Integer> incrementFunction = input -> input+1;
   static UnaryOperator<Integer> incrementFunction_2 = input -> input+1;

   static BiFunction<String, Integer, String> biFunction = (a, b) -> a + b;
   static BinaryOperator<String> concatFunction = (a, b) -> a + b;

   static BinaryOperator<Integer> max = BinaryOperator.maxBy((a,b) -> a.compareTo(b));
   static BinaryOperator<Integer> min = BinaryOperator.minBy((a,b) -> a-b);

   public static void main(Strin…