Java 8 Date Time API

Introduction to the Java 8 Date Time API

 

Java 8 introduced a new API for Date and Time. In this post, we will cover some of the features of the Java 8 Date Time API

 

Introduction

Java 1.0 introduced support for date and time using java.util.Date class.This API contains a lot of issues including not representing the date as a human-readable date but point in time with milliseconds.We will cover some of the issues or drawbacks of the existing Date API which made way for the Java 8 Date Time API

 

1.  Issues with the Existing Date Time API

  • API Design – Initial Date class introduced in Java 1.0 was not a true representation of the date but a point in time with milliseconds as precision. Calander API introduced as a replacement was poorly designed and lead to confusion in day to day use.
  • Thread Safety – The Date and Calander classes are not thread-safe.None of the instance methods are synchronized, and none of the instance fields are volatile, even get method can cause an instance of these classes as Mutable. A developer needs to ensure thread safety in case they are using these classes.
  • Usability – Most of the methods provided by Java before Java 8 Date Time API were lacking readability and needs a more clear understanding of the underlying working of the code before using it.

 

Due to all these designs flaws and inconsistencies, most of the enterprise applications were forced to use third party solution like Joda-Time etc. To resolve all these issues, Java 8 introduced a brand new Date and Time API which is integrate many of the Joda-Time API features.

 

 

2.  LocalDate, LocalTime and LocalDateTime

LocalDate, LocalTime, and LocaleDateTime are the most commonly used classes in the new Date API. These classes provide information independent of time zone i.e we do not need to worry about the time zone.

 

2.1 Working with LocalDate

LocalDate represents date without time zone in ISO format. This is one of the most commonly used classes in the new Date API.An instance of this class is immutable and represents date without information of the time and timezone.

LocalDate provides multiple utility methods to create an instance of this class. We can use of static factory method of the LocalDate class to create an instance of this class.

LocalDate date = LocalDate.of(2018, 01,8); //2018-01-08

Above code will represent the LocalDate for 8 January 2018. LocalDate instance provides a number of different methods which can be used for the most common values required while working to Date. We will cover some of the methods in this section.

 

LocalDate date = LocalDate.of(2018, 01,8);

int year = date.getYear(); //2018.
boolean isLeap = date.isLeapYear(); //f alse, 2018 is not Leap Year
int day = date.getDayOfMonth(); // 8
DayOfWeek dayOfWeek =date.getDayOfWeek(); //MONDAY
Month month =date.getMonth(); //JANUARY
int monthLength = date.lengthOfMonth(); //31
int daysOfYear = date.getDayOfYear(); // 8

 

We can use LocalDate.now() factory method to obtain current date based on the system clock.

LocalDate systemDate = LocalDate.now(); //2018-01-08

LocalDate provides other utility methods to get a different kind of information. We will cover different operations that can be performed on the LocalDate object in other section of this post.

 

 

2.2 Working with LocalTime

LocalTime represents a time of the day (e.g 20:22: 12) without time zone and date.Like LocalDate, we can get an instance of LocalTime by using the static factory method.

LocalTime time = LocalTime.of(20, 45);  //20:45
LocalTime time = LocalTime.of(20, 45, 12);  //20:45 : 12

 

LocalTime class provides numbers of utility method to get information from the LocalTime instance.

LocalTime time = LocalTime.of(20, 45, 34);  //20:45:34

int hour = time.getHour(); //20
int minutes = time.getMinute(); //45
int seconds = time.getSecond(); //34

 

To get time zone independent current LocalTime based on the system clock, we can use LocalTime.now() factory method.

LocalTime systemTime = LocalTime.now(); //20:49:35.509403

 

We can also create an instance of LocalTime by parsing String using LocalTime.parse() method

LocalTime systemTime = LocalTime.parse("15:45:45"); //15:45:45

 

 

2.3 Working with LocalDateTime

LocalDateTime is the combination of LocalDate and LocalTime. LocalDateTime represents date and time without time zone. We can create an instance of the LocalDateTime class by using now method or we can combine date and time instance to create the LocalDateTime object.

LocalDateTime localDateTime = LocalDateTime.of(2018, Month.JANUARY, 8, 21, 26, 12); //2018-01-08T21:26:12

LocalDate date= LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime combieDataIssue = LocalDateTime.of(date,time); //2018-01-08T21:30:03.663603

LocalDateTime ldt = date.atTime(time);  //2018-01-08T21:41:50.068417
LocalDateTime ldt1 = time.atDate(date);  //2018-01-08T21:41:50.068417

 

 

3.  Period and Duration

Use Duration class to represent time in seconds and nanoseconds and Period for time in years, months and days.

 

3.1 Duration

Duration is the time-based amount of time (e.g 12.4 seconds etc), here are some of the example for Duration

Duration twoMinutes = Duration.ofMinutes(3);
Duration duration = Duration.of(3, ChronoUnit.MINUTES);

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 =LocalDateTime.of(2018, Month.JUNE, 5, 10, 15, 45);

Duration duration1 = Duration.between(localDateTime1, localDateTime);

 

 

3.2 Period

A date-based amount of time in the ISO calendar system.The period class can be used to modify a value for a given date or to find the difference between dates. Let’s take an example to understand how this can be used.

LocalDate initialDate= LocalDate.of(2017, 10, 11);

 

Use period class to get useful information from the 2 date instances.

Period days = Period.ofDays(4);
Period weeks = Period.ofWeeks(3);


LocalDate initialDate= LocalDate.of(2017, 10, 11);
LocalDate finalDate =  LocalDate.of(2017, 11, 15);

int dayDuration = Period.between(initialDate, finalDate).getDays(); //4
int monthDuration = Period.between(finalDate,initialDate).getMonths();  // -1

 

 

4.  Modify Dates Instance

One of the main features of the Java 8 Date Time API is thread safety and most of the classes we discussed are immutable.In certain cases, we might need we need a new instance of the give LocaleDate instance to work with.

To create a new object for the given LocalDate, we can use one of it’s withAttribute or more generic with a method.

LocalDate currentDate = LocalDate.now(); //current system date
LocalDate withYearDate= currentDate.withYear(2017); //Returns a copy of this date with the year altered //2017-01-09

LocalDate daysOfMonth = withYearDate.withDayOfMonth(12);  // Returns a copy of this date with the day-of-month altered // 2017-01-12

 

These methods return a new object without keeping original LocalDate instance unchanged.

 

5.  Manipulate Dates

New Java 8 Date Time API provides convenient ways to manipulate LocalDate instance. We can perform add, subtract on given Date instance.

 

//Date Manipulation

LocalDate date = LocalDate.of(2017, 8, 23);
LocalDate date1 = date.plus(1, ChronoUnit.DAYS);  // 2017-08-24
LocalDate date2 = date1.plusWeeks(1);  // 2017-08-31 , one week added to date
LocalDate addYear = date2.plusYears(2);  // 2019-08-31 , added 2 years
LocalDate minusYear = date2.minusYears(4);  // 2013-08-31

LocalDate fromYear = minusYear.from(ZonedDateTime.now());

 

Please note that like with and withAttribute methods defined in the earlier section, These methods return a new Object with modified attributes.

 

 

6.  Parsing Dates

Before Java 8 parsing and formatting of Date object were not very easy. Java 8 new java.time.format package provides a lot of helpful methods to format or parse date easily.

DateTimeFormatter is one of the most important class under this package. We can use parse() method of the LocalDate instance to format given date instance.

LocalDate date = LocalDate.of(2011, 12, 17);
String formattedDate = date.format(DateTimeFormatter.BASIC_ISO_DATE); // 20111217

 

Use DateTimeFormatter for converting String to the LocalDate instance.

LocalDate stringFormattedDate = LocalDate.parse("20161217", DateTimeFormatter.BASIC_ISO_DATE); // 2016-12-17
LocalDate date1 = LocalDate.parse("2016-08-17", DateTimeFormatter.ISO_LOCAL_DATE); // 2016-08-17

 

DateTimeFormatter provides a number of formatter to work with, however,

    • what are the option if we want to format a date for which we do not have formatter provided by DateTimeFormatter class.

The DateTimeFormatter class provides a static factory method for creating custom formatter.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate currentDate = LocalDate.now(); // output : 2018-01-09

String formattedDate1 = currentDate.format(formatter); // output : 09/01/2018 in
LocalDate newDate = LocalDate.parse(formattedDate,formatter);

 

So we did few things in above example of created new LocalDate instance based on new formatter.

  • We created DateTimeFormatter for dd/MM/yyyy format.
  • We created String representation of the LocalDate instance.
  • Used parse method provided by LocalDate class to create a new instance with required format.

 

If you are looking for Local based formatter, use the overloaded method of DateTimeFormatter by passing Local as an additional parameter.

DateTimeFormatter japaneseFormatter = DateTimeFormatter.ofPattern("M'月' yyyy'年'", Locale.JAPANESE);
String newFormatter = currentDate.format(japaneseFormatter); // output : 1月 2018年
LocalDate localDate = LocalDate.parse(formattedDate1,formatter);

 

This is numbers of benefits of using this new formatter.

  • This is thread safe as compare to old DateFormat class.
  • We can use the single instance of this formatter across multiple threads.

 

The parse() method can throw DateTimeParseException in case it is not able to parse String to a valid LocalDate or LocalTime instance.

 

6.1 Using DateTimeFormatterBuilder

New Java Date and Time API provide DateTimeFormatterBuilder class to create complex formatter.

DateTimeFormatter builder = new DateTimeFormatterBuilder()
        .appendLiteral("Day of Month is :")
        .appendValue(ChronoField.DAY_OF_MONTH)
        .appendLiteral(", Month is :")
        .appendValue(ChronoField.MONTH_OF_YEAR)
        .appendLiteral(", Year is : ")
        .appendValue(ChronoField.YEAR)
        .appendLiteral(", Time is :")
        .appendValue(ChronoField.HOUR_OF_DAY)
        .appendLiteral(":")
        .appendText(ChronoField.MINUTE_OF_HOUR, TextStyle.FULL_STANDALONE)
        .parseCaseSensitive()
        .toFormatter();

LocalDateTime localDateTime = LocalDateTime.now();
String date = localDateTime.format(builder);

 

Output

Current Day is :9, Month is :1, Year is : 2018, Time is :21:16

 

 

7. Java Date Time API Features

We covered some of the basic features of Java 8 Date and Time API. There are numbers of features improvement this new API brings in, here are some of the most important features of new API.

  • Most of the classes provided by new API are immutable which is more in line with functional programming introduced with Java 8.
  • Better readability, think about Calander.getInstance() method as compare to LocalDate.now() or LocalTime().
  • The new API uses immutable objects, which makes it thread safe.

 

 

Summary

In this article, we covered Java 8 Date Time API. We covered different features and improvement introduced by Java Date and Time API. This API is a complete replacement of the old Java API and integrate many of the features of Joda-Time API.

Introduction to Java Loops

Introduction to Java Loops

Looping through an array or a collection is a very common day to day activity, in this post, we will get an introduction to Java Loops. We will be exploring various options for looping using Java.

 

Introduction

Looping is a feature which allows us to execute through a set of statements until our condition expression evaluates to false. Java provides multiple ways to Loop and choice is dependent upon the particular use case where we want to use it.

On a high level here are the options for Java Loops.

  1. for Loop
  2. While Loop
  3. Do-While Loop
  4. Enhanced for-each Loop

 

1. for Loop

A simple for loop which allows us to iterate over items until a specified condition is met or satisfied. This normally works with the help of a counter which will be initialized at the start of the execution and will be incremented with each iteration.

Based on the Java doc definition, a simple for loop have the following syntax

for (initialization; termination;increment) {
    statement(s)
}

Here are some of the important point to keep in mind while using simply for loop

  1. initialization will be done only once at the beginning of the loop.
  2. Loop will terminate when the termination condition will be evaluated as true.
  3. The increment is evaluated/ processed at each iteration.

 

Here is a very simple example

public class ForLoops {

    public static void main(String[] args) {

        for(int i=0 ;i<=6 ; i++){

            System.out.println("Value of i =" +i);
        }
    }
  
}

Output

Value of i =0
Value of i =1
Value of i =2
Value of i =3
Value of i =4
Value of i =5
Value of i =6

All three expressions for the for loop are optional which means you can easily create an infinite loop by removing all these expressions.

public class InfiniteForLoop {

    public static void main(String[] args) {

        //infinite loop by removing all expressions
        for(; ; ){

            System.out.println("Infinite Loop");
        }
    }
}

 

2. While Loop

As the name suggests, While loop will continually process statement or given code block while it’s evaluation expression is true.Here is an expression for while loop as per Java docs.

while (expression) {
    statement(s)
}

Here is a sample programme

public class WhileLoop {

    public static void main(String[] args) {

        int i = 0;

        while (i < 3) {
            System.out.println("Value of i = " + i);
            i++;
        }
    }
}

You can implement infinite while loop by setting expression as true 

public class WhileLoop {

    public static void main(String[] args) {
        while (true) {
          //your work
        }
    }
}

 

 

3. Do-While Loop

The do-while and while loop is similar and work in a similar way except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop.To put in another way, do block are always executed at least once.

public class DoWhileLoop {

    public static void main(String[] args) {

        int i = 0;
        do {
            System.out.println("Value of i = " + i);
            i++;
        } while (i < 5);
    }
}

 

4. Enhanced for Loop

Java 5 introduced a variation of the for loop known as enhanced for-loop.It provides a simple way to iterate over the elements of array/collection.Here is a syntax for the enhanced for loop

for(Type item : items){
    //Business rules
}

In order to use this loop, we only need to define following 2 things

  1. Type to hold element being iterated.
  2. Source of the iteration

We are no longer required to declare iteration index to loop through the element as this will be taken care internally by JDK. Here is an example demonstrating difference between simple for loop and enhanced for loop in Java

public class EnhancedForLoop {

    public static void main(String[] args) {
        
        List<String> stringList= Arrays.asList("One", "Two","Three");
        
        //in old for loop
        for(int i =0 ; i<= stringList.size() ; i++){
            System.out.println("List Value is "+stringList.get(i));
        }
        
        //with enhanced for loop
        for(String value : stringList){
            System.out.println("List Value is "+value);
        }
    }
}

 

4.1 Iterable.forEach()

We are already into Java 9 and it will not be good if we do not cover new enhancement introduced in Java 8.We have now a default method named forEach() added to the java.lang.Iterable<T> interface with an ability to accept lambda expressions.

Let’s take our earlier example and see how this can be redefined by utilizing new Java 8 feature

public class ForEachJava8 {

    public static void main(String[] args) {

        List<String> stringList= Arrays.asList("One", "Two","Three", "Four");

        //Before Java 8

        for(String value : stringList){

            //work will be done here
        }

        // With Java 8 and Lambda Expressions

        stringList.forEach(name -> System.out.println(name));

    }
}

As we saw, with introduction of Lambda Expression in Java 8, we were able to iterate through element using a single line of code

stringList.forEach(name -> System.out.println(name));

I will be covering benefits of Lambda and parallel execution in some other post.Read our article Lambda Expressions in Java to start with Java 8 Lambda Expressions.

Summary

In this post, we discussed different Java Loops. We covered new enhancement introduced in Java 5 for enhanced for loop along with the new features introduced with Java 8. You can download the examples from Github

How to Kill Java Thread

How to Kill Java Thread

In this article, we will discuss the clean way to Kill Java Thread, this is really necessary to understand as Java had already deprecated Thread.stop() methods.

 

Introduction

Oracle deprecated Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit due to some of the underlying thread safety issues.  There are few recognized and well-accepted ways to accomplish this and in this article, we will be covering 2 approached to Kill a Thread in Java.

  • Using a Flag
  • Interrupting a Thread.

 

1. Use a Flag

One of the easy approaches is to use thread to indicate if a Thread is running or not and use this flag to take corrective action based on your requirement, here is a sample code outlining how to Kill Java Thread using a flag.

public class KillThreadUsingFlag implements Runnable {


    private final AtomicBoolean running = new AtomicBoolean(false);
    private Thread thread;

    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        while (running.get()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
        System.out.println("Shutting down thread");
    }

    public void shutdown() {
        running.set(false);
    }

    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    public static void main(String[] args)
            throws InterruptedException {
        KillThreadUsingFlag process = new KillThreadUsingFlag();
        process.start();
        Thread.sleep(5000);
        process.shutdown();
    }
}

In the above example. we can control execution by setting our running variable to false.In our example, we have used AtomicBoolean for concurrency, in case you do not want to use it (which is not recommended), you need to make sure that Boolean flag used by you in your code should be volatile.

 

2. Interrupting a Thread

Above code looks good but have some main points which need to be taken into account before we take above approach

  • It will become more complicated in case we have lots of threads and we need to ensure that those are finished by using join() method.
  • Do we really need to define a Boolean flag as Java already provide this feature using interrupted flag?
public class InterruptedExceptionExample implements  Runnable {


    private final AtomicBoolean running = new AtomicBoolean(true);


    /**
     * When an object implementing interface <code>Runnable</code> is used to create a thread,
     * starting the thread causes the object's <code>run</code> method to be called in that
     * separately executing thread. <p> The general contract of the method <code>run</code> is that
     * it may take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try{

            while (running.get()){
                for(int i =0; i<3 ; i++){
                    System.out.println(i);
                }

                Thread.sleep(2000);
            }
        }
        catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(new InterruptedExceptionExample());
        Thread.sleep(3000);
        executor.shutdownNow();
    }
}

 

There are couple of things which are really important in this code block

  • We are not swallowing the exception but passing it on to the system to ensure corrective action is being taken by system based on this exception

In the above example, we caught InterruptedException and immediately used Thread.currentThread().interrupt()  to interrupt our thread immediately.This is required since the interrupted flag is cleared once the exception is thrown and it can cause some issue in case our code is running in the nested loop.

Just to summarize, Thread.interrupt() is the preferred/recommended way to cleanly Kill Java Thread if you still want to use flag approach you may have to wait for all the blocking operations to finish before you can use your flag based logic.

 

Summary

Java Concurrency is always always a complex part of the JDK and working with threads can add more complexity if we are not aware of the inner working mechanism of the JDK. In this post, we covered different ways to Kill Java Thread. We discussed a flag based approach to handle this and finally, we covered mechanism of interrupting a thread which is known as better and cleaner way to shut down threads in Java.

Functional Interfaces in Java 8

Functional Interfaces in Java 8

This post works as an introduction to the Functional Interfaces in Java 8. We will be covering some of the basics of the Functional Interfaces introduced in Java 8.

 

Introduction

Java has always been called as OOP (Object Oriented Programming) language. Functions do not exist independently in Java and everything is part of Class and use to class/object to invoke any function (ie, JNI). Functional Programming Language is written independent functions and uses them when required such as C++, JavaScript.

Function Interface was introduced in Java8 as new features along with Stream API, Time API, Lambda Expression, etc., Function Interface having only one abstract method which means interface contains only one abstract method and it can have multiple default methods.

 

1.FunctionalInterface Example 

@FunctionalInterface annotation was introduced along with other annotation in Java 8 which can be used to validate at the compile time that can’t have more than one method beside default.

Let’s create a simple example to understand few details of the @FunctionalInterface.

@FunctionalInterface
public interface Account {

    int returns();

    default void printDetails() {
        System.out.println("Default Methods");
    }
}

An interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere (ie., abstract methods that override the method in the object).

@FunctionalInterface
public interface Account {

    int returns();

    default void printDetails() {
        System.out.println("Default Methods");
    }

    /*
     * Overridden from Object class
     */
    public String toString();

    public int hashCode();

}

FunctionalInterface annotation is not mandatory to use because of the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

Java earlier version having a single abstract method in the interface and they were known as simple abstract method interface e.g.,Runnable Interface (Run method), Comparator Interface.

 

2.Functional Interfaces Type 

The declaration of a functional interface allows a functional interface type to be used in a program by the developer and these are segregated as four kinds of functional interface type based on a declaration.

 

Another interesting part is Interface can extend another interface and In this scenario, Interface extending in functional and it doesn’t declare any new abstract methods then the new interface is functional which will satisfy the definition.

public interface Bank {

    public void openAccount();
}

Account interface extends Bank interface which has only one OpenAccount method and Account interface doesn’t have any abstract method but still, it is valid functional Interface.

@FunctionalInterface
public interface Account extends  Bank {}

Let see one more example, consider while inherits two abstract which have the same signature.

public interface SocialMedia {
  public void OpenAccount();
}

In this case, still, the inherited methods logically represent a signal method so Account is a function interface.

@FunctionalInterface
public interface Account extends SocialMedia {
}

 

Consider above example, if one is return type substitutable then Account causes compile time error because it’s inheriting two methods.

 

interface Bank {public void OpenAccount();}
interface SocialMedia {public boolean OpenAccount();}

There are numbers of functional interfaces defined under java.util.function package, some of the useful interfaces are

  • Consumer
  • Function
  • Supplier
  • Predicate

 

2.1  Predicate Example

import java.util.function.Predicate;;

/**
 * @author Arunchandu
 */
public class PredicateTestExample {

    public static void main(String[] args) {

        Predicate<String> i = (name) -> name.contains("java");
        System.out.println(i.test("Thank you for Learning from javadevjournal.com"));
    }

}

 

2.2  Pass Function Example

import java.util.function.Function;

public class PassFunction {

    public static void main(String[] args) {
        int percentage = 5;
        String result = calc((amount) -> "Tax : " + ((amount * 100) / percentage), 10);

        System.out.println(result);

    }

    public static String calc(Function<Float, String> bi, float i) {
        return bi.apply(i);
    }

}

 

Summary

In this post, we got an introduction to the Functional Interfaces in Java 8. We covered some of the aspects of functional interfaces along with few interesting functional interfaces introduced in Java 8.

If you are starting with Java 8, read our following articles on Java 8

  1. Introduction to Java 8 Streams
  2. java 8 optional
  3. Java 8 StringJoiner

Introduction to Java 8 Streams

Introduction to Java 8 Streams

In this post, we will get a quick Introduction to Java 8 Streams API, a new feature introduced in Java 8.We will try to get a high level of understanding as what is stream and how this can be used in our day to day work.

 

Introduction

Streams are one of the most important APIs introduced in Java 8 and completely changes the way we do processing of Collections in Java. This is in line with the theme of Java since past few versions where advances in hardware are exploited by the language.

 

1. Why Java 8 Streams

Before diving into ‘What’ of Streams, let us get into ‘Why’. Why were Streams introduced and what
problem they solve?

Let us see the code below:

private static HashMap<String, Integer> myIterator(List<String> inList) {
    Iterator<String> thisIterator = inList.iterator();
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    while (thisIterator.hasNext()) {
        String str = thisIterator.next();
        if (str.length() > 5) {
            map.put(str, str.length());
        }
    }
    return map;

}

Above code is not doing anything fancy or complicated but it takes in a List of String, calculates the length of each String in List and puts the String, String Length in a HashMap if length greater than 5. It is definitely solving our problem but there are multiple problems with above code.

  1. The code is sequential in nature and in spite of my computer being a Quad core system, I am not exploiting computer’s processing power here.
  2. Simply, too much code for a simple task.
  3. As a programmer, I need to work on the lower level aspects of the program. I have to take care of ‘how’ the iteration takes place apart from the program logic. Such programmer driven iteration is called External Iteration. It can have optimization issues in complex and data-intensive programs.

 

2. Code Simplifaction using Java Streams

Java Streams help us address the above-mentioned issues by completely abstracting out the low-level parallelism logic and Iteration logic.Putting in the most simple way, Java Streams convert Collections to a Stream, process the elements in parallel by performing multiple operations and again gather the final elements into a Collection.

Java Stream API helps us do above mention by implementing internal iteration. It lets the framework perform a sequential and parallel execution, mapping elements and criteria based filtering. Java framework is in control of the resulting iteration and lets the developer fully concentrate on the data and various operations to be performed on it.

Java Stream API implements functional interfaces as its API methods, which ties up well with Lambda expressions, which is another pillar of Java 8. Together they make the Java 8 a true ‘functional’ language.

Thus, when we use Java Streams, the code mentioned above turns into a single line code.


private static Map<String, Integer> myIterator(List<String> inList) {

    return inList.stream().filter(str -> str.length() > 5).
            collect(Collectors.toMap(str -> str, str -> str.length()));
}

Here inList is a List of Strings. Stream method takes the inList and streams it into a filter. Filter passes only those Strings which meet the criteria (String.length>5). Collect method takes in the filtered Strings and sends them to Collector.toMap() function which inserts the String and their Lengths in the Map.

In a single line of code, we utilize the Streaming, Filtering and Collection mechanisms of the API thus writing a more efficient code.

 

3. Steams API Benefits

let’s see other important aspects of Streams.

Streams are on-demand Data Structures. They don’t store data and instead take in a Data Structure(mainly Collections) as the source to produce a pipeline of that Collection. On this pipeline, desired functions can be called further to harness the power of in-memory computation.

Streams support Parallel Processing and Sequential Processing both, giving the developer options to use whatever mechanism as per the requirement. For large collections, Parallel Processing can work wonders in terms of achieving great performance.

Streams support Lazy computation, that means we do these operations only when we need it and not when they are defined in the Streams.This leads to higher performance and optimization of the programs than the traditional methods.

Streams have two types of Operations: Intermediate and Terminal. All those Stream operations which return a new Stream are called intermediate operations. These never return the final result of the operations and help in building a pipeline from one operation to another. filter and map are two such operations.

All Stream operations which return a result are Terminal operations. They are eager computations which process Stream elements before returning results and they consume the Stream. After consumption by these operations, Streams are no more available for further processing. They can be identified by their return types as they would not produce any further Streams. Examples are:forEach, toArray, min, max etc.

 

Summary

This was a very high level and a brief Introduction to Java 8 Streams API. We discussed what are the benefits and features brought by Java Streams and how they can be utilized to write more concise and easily readable code.

Stay tuned to our website for further content on Streams and other in-depth content in Java.If you are interested to learn about new features of Java 8, read 

Java 8 optional

Java 8 StringJoiner

Math.pow in Java

Using Math.pow in Java

In this quick post, we will get an understanding of Using Math.pow in Java. power of the number in a very simple term indicates as to how many times to use a number for multiplication.

 

1.  Example

Math.pow have a very simple signature like

public static double pow(double a, double b), where 'a' indicates the base,  'b' indicated the exponent and Math.pow() will return the value as 

ab

Let’s look into a very simple example to understand how Mah.pow works.

@Test
public void calculateIntPow(){
    int a= 3;
    int b=4;

    int result = (int) Math.pow(a,b);

    assertEquals(81, result);
}

Since we were expecting results in an int, it was required to cast the output to int to get desired results.We are not required to cast results in case desired output is in double (which is also output for  of the Math.pow() method)

@Test
public void calculateDoublePow(){
    double a= 3.4;
    int b=4;

    double result =  Math.pow(a,b);

    assertEquals(133.63, result, 2);
}

There are certain features/properties of this method, read  Math.pow for more detail.

Summary

In this quick post, we get an understanding as to how to Use Math.pow method in Java to calculate the power of any given base.

Initializing Arrays in Java

Initializing Arrays in Java

In this post, we will cover different options for Initializing Arrays in Java along with main differences with each option.

 

Introduction

In this post, we will be covering some of the commonly used ways for Initializing Arrays in Java, we will also discuss briefly these different options and subtle differences between them.

 

1. Initializing using Loop

One of the simplest ways is to initialize an array using a loop, this method will fill one element at a time in the Array.

for( int i=0; i< length ; i++){
    data[i] = i;
}

 

2. Initializing During Declaration

If we know about the size and element of the array, we can also initialize it at the declaration time.

int[] data = {101,201,130,401,350,660,771,880,890,891};

int[] data;
data = new int[] {100,200,300,400,500,600,710,800,900,912};

String[] strings = new String[] {"Sunday", "Monday","Tuesday"};

Please be aware the with above syntax, you will not be able to initialize after this, the system will be throwing a compile-time error if we will try to do this.

 

3. Arrays.fill()

Arrays class contains various methods for manipulating arrays, we can use any of the Arrays.fill() method to fill given the array with the same value.

long array[] = new long[15];
Arrays.fill(array, 20);

There are multiple variations of the fill method which can be used based on the requirement.

 

4. Arrays.setAll()

These methods set all elements of the specified array, using the provided generator function to compute each element.

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

 

Summary

In this short post, we covered different options to Initializing Arrays in Java. These are handy techniques and commonly used in the day to day development.

Java 8 StringJoiner

Introduction to Java 8 StringJoiner

In this short post, we will be covering Java 8 StringJoiner feature and will explore what are the different features and how this can be used more effectively with Java 8 Stream API.

 

Introduction 

Joining multiple strings in a very common tasks in day to day programming activity.There was no direct way to join multiple String in Java (Other than using the third party API’s). Java 8 Introduced a new class StringJoiner which can be used to join multiple Strings.StringJoiner is a kind of a Collector.

 

1. StringJoiner

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

 1.1 Using Delimiter

One of the common use cases of the StringJoiner is to use a delimiter to join strings.

StringJoiner joiner = new StringJoiner(",");
    joiner.add("Sunday");
    joiner.add("Monday");
    joiner.add("Tuesday");

 System.out.println(joiner.toString());

Here is our Junit Test

@Test
public void stringJoinerTest(){

    StringJoiner joiner = new StringJoiner(",");
    joiner.add("Sunday");
    joiner.add("Monday");
    joiner.add("Tuesday");

    assertEquals("Sunday,Monday,Tuesday", joiner.toString());
}
 1.2 Using Delimiter, Prefix and Suffix

StringJoiner also provides the way to predefined prefix and suffix in addition to the delimiter.

public static void joinerWithDelimiterWithPrefixAndSuffix(){
    StringJoiner joiner = new StringJoiner(",", "Prefix-", "-Suffix");
    joiner.add("Sunday");
    joiner.toString();
}

Output 

Prefix-Sunday-Suffix

 

 1.3 Join Multiple StringJoiner

We can also merge multiple StringJoiner using StringJoiner’s merge() method

   StringJoiner joiner1= new StringJoiner("|");
   StringJoiner joiner2= new StringJoiner(";");
   StringJoiner joiner3= new StringJoiner(";");

   joiner2.add("one");
   joiner2.add("two");
   joiner1.merge(joiner2);

   joiner3.add("three");
   joiner3.add("four");
   joiner1.merge(joiner3);

   System.out.println(joiner1.toString());

Output

one;two|three;four

 

2. String.join()

StringJoiner is used internally by two static String.join methods

String output= String.join("-", "2017","09","30");
2017-09-30 //output
List<String> list= Arrays.asList("one","two","three");
String output = String.join("-", list);

one-two-three //output

4. Collectors.joining

StringJoiner can be easily used with the new Java 8 Collection API.

List<Customer> customers = Arrays.asList(
        new Customer("John", "Smith"),
        new Customer("Umesh", "Awasthi"),
        new Customer("Andy", "Flower")
);

final String customerJoin = customers.stream()
        .map(Customer::getFirstName)
        .collect(Collectors.joining(","));

System.out.println(customerJoin);

Output

John, Umesh, Andy

 

5. Why StringJoiner

There can be a very natural question about why do we need StringJoiner when we already have StringBuilder? Or it internally use StringBuilder to perform most of the operations

With the Java 8 Stream API, StringJoiner is very useful as compared to the StringBuilder.Let’s take an example to understand the difference between using SpringJoiner and StringBuilder.

List<String> list = Arrays.asList("Foo","Bar");

//join string using StringJoiner
String output = list.stream().collect(Collectors.joining(","));

//using StringBuilder

String collectoutput =
        list.stream().collect(Collector.of(StringBuilder::new,
                (stringBuilder, str) -> stringBuilder.append(str).append(", "),
                StringBuilder::append,
                StringBuilder::toString));

 

Summary

In this post, we got an Introduction to Java8 StringJoiner. We explored various features of the StringJoiner class and how to use it to join multiple Strings.We can also think of StringJoiner as a kind of Collector and can be really useful when working with parallel streams.

Convert a Map to List in Java

Convert a Map to List in Java

In this post, we will learn as how to Convert a map to List in Java.We will see how to do this using JDK.

 

1. Conventional Method

To convert, Java Map to List, we can use the conventional constructor with ArrayList, however, there are few things to consider before we proceed with the conversion. 

 Java Map has 2 values while list contains only single value while converting Map to list, we need to take a call of converting either map values or keys, so either we will get a map of keys or list of values (we can get both by using some wrapper to have both values).

public class MapToList {

    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        //Convert Map keys to List
        List<Integer> keyList= new ArrayList<Integer>(map.keySet());
        keyList.forEach(key-> System.out.println(key));

        //Convert Map values to List
        List<String> valueList= new ArrayList<String>(map.values());
        keyList.forEach(value-> System.out.println(value));

    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

Output for the above programme will be

1
2
3
4

For valueList

Sunday
Monday
Tuesday
Wednesday

2. Using Java 8

We can also use Java 8 Stream API to convert Map to List in Java.

public class MapToListJava8 {

    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        List<Integer> keyList=map.keySet().stream().collect(Collectors.toList());
        keyList.forEach(key-> System.out.println(key));

        List<String> valueList=map.values().stream().collect(Collectors.toList());
        valueList.forEach(value-> System.out.println(value));
    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

My preference will be for the constructor based approach as it is more straight forward and easy to read rather than the Java 8 Stream API.

3. Summary

In this post, we explored as to how to convert a Map to List in Java, we learned how to convert it using a constructor and Java 8 Stream API.We can use a similar technique to convert Map to Set which we will cover in another post.

All the code of this article is available Over on Github. This is a Maven-based project.

Spring Profiles

Introduction to Spring Profiles Using Spring Boot

In this post, we will be exploring Spring Profiles using Spring Boot and will see how we can use it efficiently in our project.

 

Introduction

Spring Profiles provides a powerful and easy way to control code and configuration based on the environment. Using Spring Profiles it’s possible to segregate parts of our application and make it only available in certain environments. We can use @Profile annotation to limit the availability of any @Component  or @Configuration.

 

1. Use @Profile Annotation

Main entry point for the Spring Profile is @Profile annotation which can be used to group things together. Let’s take a simple example for a Database connection bean where we want to make sure that certain DB connection should be active only in DEV mode but not in production or QA / Staging. We can use @Profile annotation to achieve this.

@Service
@Profile("development")
public class DevDBConnection implements  DatabaseService {
    
    @Override
    public void getDBConnection() {
        System.out.println("DEV DB connection established");
    }
}

Since we annotated DevDBConnection bean with “development” profile, it will only be available in the Spring container if development profile is active, in other words, if development profile is not active, this bean will not be available/active.  

Default profile used by Spring profile is the default. All the beans with no profile annotation are specified belongs to the default profile. We can also set default profile in Spring Boot by  @Profile("default") or @Profile({"default","development"}).

 

2. Use @Profile Annotation

Spring Boot provides multiple ways to active profile. We can pass profile information through the command line or use application.properties, Spring Boot also provide a way to set profile programmatically.

2.1 Using Command Line

We can pass profile information to Spring Boot using the switch through command prompt —spring.profiles.active=development,staging

 
2.2 Using Property File

We can use standard Spring environment property spring.profiles.active property in our application.properties or application.yaml to specify active profiles.

spring.profiles.active=development,staging
 
2.3 Programmatically setting profile

We can programmatically set active profile by calling setAdditionalProfiles(...) method provided by SpringApplication class

SpringApplication app = new SpringApplication(Application.class);
app.setAdditionalProfiles("development","production");

Take a note that spring.profiles.active property follows same ordering rule as followed by other properties defined by Spring Boot. Highest property source will overwrite any other property defined in the hierarchy. Please refer to Spring Boot documentation to understand how Spring Boot read these properties.

3. Profile Specific Configurations

One of the most interesting and powerful features provided by Spring Boot is the ability to define profile specific application.properties file and active these by main application.properties file.

To use profile specific configuration files, we need to the naming convention of application-{profile}.properties where profile defines the name of the intended profile. Profile specific files will be loaded from the same location as application.properties file, also be aware that profile specific properties will override properties defined in the default application.properties irrespective of whether the profile-specific files are inside or outside your packaged jar.

To understand it completely, let’s take the same example of Database configuration where we want to define different DB configurations for Development and Production.To achieve this using configuration files, we will define 2 configuration file namely application-production.properties and application-development.properties. 

application-production.properties

db.url=jdbc:oracle:thin:@<host>:1521:<sid>
db.driver=oracle.jdbc.driver.OracleDriver
db.username=<username>
db.password=<password>
db.tableprefix= 

application-development.properties

db.url=jdbc:hsqldb:file:configurations
db.driver=org.hsqldb.jdbcDriver
db.username=sa
db.password=
db.tableprefix=

In above example we used HSQL for Development while we want to use Oracle for production and based on the active profile, we can easily switch DB configurations.

Please read @ConfigurationProperties in Spring Boot to understand how Spring Boot Configuration works

4. Complete Example

Here is a complete example to understand how Spring Boot Profile work.

DataBase Service

public interface DatabaseService {

    void getDBConnection();
}

Development Profile

@Service
@Profile("development")
public class DevDBConnection implements  DatabaseService {

    @Override
    public void getDBConnection() {
        System.out.println("DEV DB connection established");
    }
}

Production Profile

@Service
@Profile("production")
public class ProdDBConnection implements DatabaseService {

    @Override
    public void getDBConnection() {
        
        System.out.println("Product DB connection establish");
    }
}

Spring Boot Runner

@SpringBootApplication
public class SpringbootTutorialsApplication implements CommandLineRunner{

   @Autowired
    DatabaseService databaseService;

    public static void main(String[] args) {

      SpringApplication.run(SpringbootTutorialsApplication.class, args);
   }

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        databaseService.getDBConnection();
    }
}

output

if you run above example with development profile as active profile, we will have the following output

DEV DB connection established

5. Conclusion

In this post, we covered Spring Profile features, we learned how to use Spring Profile in Spring Boot using different options.Spring profile is a powerful way enable right profile in our application, ability to define profile specific configuration files in Spring Boot gives a lot of flexibility to manage our applications.