Using Java8 Features

Using new java.time.* API classes bundled with Java 8

Server Time


Servers should almost always be set to a UTC/GMT time zone without Daylight Saving Time. 

 -> If possible avoid Usage of java.util.Date because this package does not have Timezone support ! 

The java.util.Date & .Calendar classes bundled with Java are notoriously troublesome.

One of the pain points is that while a Date has no time zone assigned, its  toString method uses the default time zone 
in rendering the string. So to the naïve programmer it  seems like Date has   a time zone when it does not. 

Use either the Joda-Time library or the new java.time.* classes bundled with Java 8

Code Sample : Loop through a Hashmap

 Definiton Hashmap 
  static  Map semPlanMap = new HashMap();

 Load the Hashmap  
  private void resetData() {
         LOGGER.warn("resetData() called");
         semPlanMap.put(1, new SemesterPlan(1, 27,12, "nein"));
         semPlanMap.put(2, new SemesterPlan(2, 28,14,"nein"));
         semPlanMap.put(3, new SemesterPlan(3, 29,0,"nein"));

 Loop throught the Hashmap
 int getVacatingSemesterCount() {
        int vacationSemesterCount = 0;
        for(Map.Entry entry : semPlanMap.entrySet()){
            SemesterPlan s =  entry.getValue();
            if (s.isVacationSemester.equals("ja")) {
                LOGGER.warn("Found a Vaction Semster___________ Key : " + entry.getKey() + "  and Value: " + entry.getValue());
                vacationSemesterCount++;
            }
        }
        LOGGER.warn("________________  No of Vacation Semesters found " + vacationSemesterCount );
        return vacationSemesterCount;
    }

For-Each Example: Enhanced for Loop to Iterate Java Array

Reference

Java8 Feature Lambda Expression, Function Reference

Overview Java8 Feature Lambda Expression, Function Reference

  • In a method reference, you place the object (or class) that contains the method before the :: operator and the name of the method after it without arguments.
  • First of all, a method reference can’t be used for any method.
  • They can only be used to replace a single-method lambda expression.
  • To use a lambda expression, you first need a functional interface, an interface with just one abstract method.
  • Method references are expressions which have the same treatment as lambda expressions (…), but instead of providing a method body, they refer an existing method by name.

In other words:

  • Instead of using -> AN ANONYMOUS CLASS
  • you can use -> A LAMBDA EXPRESSION
  • And if this just calls one method,you can use -> A METHOD REFERENCE

Overview Consumer Interface

  • In java, the Collection interface has Iterable as its super interface – and starting with Java 8 this interface has a new API: void forEach(Consumer action)
  • The Consumer interface is a functional interface (an interface with a single abstract method). It accepts an input and returns no result.
 
@FunctionalInterface
public interface Consumer {
    void accept(T t);
}

Java Code

import java.util.List;
import java.util.function.Consumer; 

public class ForEachTest{
  public static void main(String args[]){
    List names = new ArrayList<>();
    names.add("Larry");
    names.add("Steve");
    names.add("James");
	
    System.out.println("-> Testing  Annonymous Class ");
    run(names);
	
	System.out.println("-> Testing Lambda Notation");
	runLambda(names);
	
	System.out.println("-> Testing Function Reference");
	runFuncRef(names);
  }
  
  public static void runFuncRef( List names ) {
	names.forEach(System.out::println);
  }
  
  public static void runLambda( List names ) {
    Consumer consumerNames = name -> { System.out.println(name); };
    names.forEach(consumerNames);
  }

  public static void run( List names ) {	
	names.forEach(new Consumer() {
		public void accept(String name) {
			System.out.println(name);
		}
	});
  }
}

Output

D:\dev\JAVA8\FunctionRef> java ForEachTest
-> Testing  Annonymous Class
Larry
Steve
James
-> Testing Lambda Notation
Larry
Steve
James
-> Testing Function Reference
Larry
Steve
James 

Reference

Usage of apply() method of java.util.function.Function

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

class Employee {
	String name;
	int age;
	Employee( String name, int age ) {
		this.name = name;
		this.age = age;
	}
	String getName() { return name; }
}

public class FunctionTRExample{
  public static void main(String args[]){
    Function funcEmpToString= (Employee e)-> {return e.getName();};
    List employeeList= 
     Arrays.asList(new Employee("Tom Jones", 45), 
      new Employee("Harry Major", 25),
      new Employee("Ethan Hardy", 65),

    List empNameList=convertEmpListToNamesList(employeeList, funcEmpToString);
    empNameList.forEach(System.out::println);
	}
 
 public static List convertEmpListToNamesList(List employeeList, Function funcEmpToString){
   List empNameList=new ArrayList(); 
   for(Employee emp:employeeList){
     empNameList.add(funcEmpToString.apply(emp));
   }
   return empNameList;
  }
}

Output:

D:\dev\JAVA8\FunctionRef>  java FunctionTRExample
Tom Jones
Harry Major
Ethan Hardy

Explanation of above example’s Code & Output

  • funcEmpToString is an instance of Function. This is the java.util.function.Function instance which is used to convert/map from an Employee object to a String value.
  • The lambda defining funcEmpToString is – (Employee e)-> {return e.getName();} . It takes as input an Employee object and returns his\her name, which is a String value, as output.
  • The list of employees is passed to method convertEmpListToNamesList() along with the Function object funcEmpToString;
  • The method convertEmpListToNamesList() iterates over all the employees in the employee list, applies the function funcEmpToString to each of the Employee objects, getting back the employee names in String format, which it puts in a employee name list and sends it back to the main() method.
  • On printing the employee name list we get the names of all the employees as required.

Reference

Usage of andThen() method of java.util.function.Function

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

class Employee {
	String name;
	int age;
	Employee( String name, int age ) {
		this.name = name;
		this.age = age;
	}
	String getName() { return name; }
}

public class FunctionTRAndThenExample{
  public static void main(String args[]){
    Function funcEmpToString= (Employee e)-> {return e.getName();};
    List employeeList=
     Arrays.asList(new Employee("Tom Jones", 45), 
      new Employee("Harry Major", 25),
      new Employee("Ethan Hardy", 65),
      new Employee("Nancy Smith", 15),
      new Employee("Deborah Sprightly", 29));
    Function initialFunction= (String s)->s.substring(0,1);
    List empNameListInitials=convertEmpListToNamesList(employeeList, funcEmpToString.andThen(initialFunction));
    empNameListInitials.forEach(str->{System.out.print(" "+str);});
 }
  public static List convertEmpListToNamesList(List employeeList, Function funcEmpToString){
   List empNameList=new ArrayList(); 
   for(Employee emp:employeeList){
     empNameList.add(funcEmpToString.apply(emp));
   }
   return empNameList;
  }
}

Output:

D:\dev\JAVA8\FunctionRef>  java FunctionTRAndThenExample
 T H E N D

Explanation of above example’s Code & Output

  • Function instance funcEmpToString maps\converts an Employee object to a String of his\her name.
  • Function instance initialFunction maps\converts a String to its initial or first letter.
  • Default method andThen() is used to combine initialFunction with funcEmpToString. What the combined method does is that it first maps an Employee to his\her name and then takes out the first letter from the name as a String value. This combined function is passed as Function parameter to convertEmpListToNamesList() method along with the employee list.
  • When the convertEmpListToNamesList() applies the combined function to each of the Employee objects, then the result is a String list first letters of names of each employee.
  • This is the required output i.e. T H E N D

Reference

Java8 Feature Streams map()

/*
*   Reference:  Java 8 Streams map() examples 
*               https://www.mkyong.com/java8/java-8-streams-map-examples/ 
*/

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TestJava8Stream {

    public static void main(String[] args) {

        List alpha = Arrays.asList("a", "b", "c", "d");

        //Before Java8
        List alphaUpper = new ArrayList<>();
        for (String s : alpha) {
            alphaUpper.add(s.toUpperCase());
        }

        System.out.println("Original Data:                  " + alpha); //[a, b, c, d]
        System.out.println("Data Conversion via for Loop:   " + alphaUpper); //[A, B, C, D]

        // Java 8
        List collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("String Conversion via Streams:  " + collect); //[A, B, C, D]

        // Extra, streams apply to any data type.
        List num = Arrays.asList(1,2,3,4,5);
		System.out.println("Original Number Data         :  " +  num); //[1, 2, 3, 4, 5]
        List collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
        System.out.println("Number Conversion via Streams:  " +  collect1); //[2, 4, 6, 8, 10]
    }
}

Output:

D:\dev\JAVA>javac TestJava8Stream.java

D:\dev\JAVA>java TestJava8Stream
Original Data:                  [a, b, c, d]
Data Conversion via for Loop:   [A, B, C, D]
String Conversion via Streams:  [A, B, C, D]
Original Number Data         :  [1, 2, 3, 4, 5]
Number Conversion via Streams:  [2, 4, 6, 8, 10]

Reference

Intellij Warning: Statement lambda can be replaced with expression lambda

Java code:

    tearboxMessagesAfterTest.forEach((TearboxMessage tbMsg) -> { assertNull(tbMsg.getAccount()); });
  • Intellij Warning: Warning:(164, 68) Statement lambda can be replaced with expression lambda

Modifed Java Code [ Remove curly brackes + semicolon ! ]

	tearboxMessagesAfterTest.forEach((TearboxMessage tbMsg) -> assertNull(tbMsg.getAccount()) );