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

Lambda Expressions in Java

Lambda Expressions in Java

In this post, we will be discussing  Lambda Expressions in Java, a new feature introduced in Java 8.

 

Introduction

Added in Java 8, lambda expressions enhance the Java performance by increasing the expressive power of the language.

Before getting into Java Lambda Expressions, first, we need to understand what is a functional interface.

If a Java interface that contains one and only one abstract method then it is termed as the functional interface. This only one method specifies the intended purpose of the interface. For example, the Runnable interface form package java.lang; is a functional interface because it constitutes only one method i.e. run()

Here’s how you define a functional interface:

@FunctionalInterface
public interface MyInterface{
    double getValue();
}

However, the @FunctionalInterface annotation is not necessary, but it is wise to use it because it forces the Java compiler to indicate that the Interface defined is a functional interface and it must have only one abstract method. The functional interface is sometimes referred as Single Abstract Method or SAM type.

For more information, read our post on Functional interfaces in Java.

 

1. What are Lambda Expressions

Lambda expression is, essentially, an anonymous or unnamed method. The lambda expression does not execute on its own. Instead, it is used to implement a method defined by a functional interface.There will be a natural question “How to define lambda expression in Java?” 

The lambda expression introduces a new syntax element and operator in Java language. The new operator is referred to as the lambda operator or the arrow operator. Which is ->

Let’s write a simplest lambda expression which just returns a constant double value.

() -> 3.1415

The above lambda expression syntax is equivalent to the following method:

double getPiValue() { return 3.1415; }

 

The left side of the expression specifies any parameters required by the expression, whereas the right side is the lambda body, which specifies the action of the lambda expression.

 

2. Lambda Body

The lambda body is of two types.

  1. A body with a single expression () -> System.out.println(“Lambdas are great”);
  2. A body that consists of a block of code. () -> { double pi = 3.1415; return pi; }

 

A lambda expression can also have parameters. For example: (n) -> (n%2)==0

 

This lambda expression evaluates it the value of n is even or odd.If lambda body is a code block, you must always return a value explicitly. But, if lambda body is an expression, return statement is not required. Let’s write some practical Java code with lambda expression which simply returns the value of Pi. As mentioned earlier, the lambda expression is not executed on its own. Rather, it forms the implementation of the abstract method defined by the functional interface.

 

So, first define a functional interface (MyInterface.java):

import java.lang.FunctionalInterface;

// This is functional interface
@FunctionalInterface
public interface MyInterface {
    double getPiValue();
}

Now, we assign the lambda expression to the instance of the functional interface.

public class LambdaMain {
    public static void main(String[] args) {
        // create a reference to MyInterface instance.
        MyInterface myInterface;

        // use lambda in assignment context
        myInterface = () -> 3.1415;


        // call getValue() from myInterface instance, which is implemented by the previously assigned lambda expression
        System.out.println("Value of Pi = " + myInterface.getValue());
    }
}

When you run the program, the output will be:

Value of Pi = 3.1415

 

The lambda expression must be compatible with the abstract method. This means if you assign () -> “3.1415” to the myInterface instance, the code is illegal and won’t work because the type of String is not compatible with the double as defined in the functional interface.

Let’s look at some other lambda expression example that takes in a parameter.

// MyInterface.java
@FunctionalInterface
public interface MyInterface {
    String reverse(String n);
}
// ParamLambdaMain.java
public class ParamLambdaMain {
    public static void main(String[] args) {
        MyInterface myInterface = (str) -> {
            String result = "";
            for (int i = str.length() - 1; i >= 0; i--)
                result += str.charAt(i);
            return result;
        };

        System.out.println("Lambda reversed = " + myInterface.reverse("Lambda"));
    }
}

When you run the program, the output will be:

 

Lambda reversed = adbmaL

 

The above functional interface only accepts String and returns a string. However, we can make the functional interface generic, so that any value is accepted.Let’s look at how it’s done:

// GenericInterface.java
@FunctionalInterface
interface GenericInterface<T> {
    T func(T t);
}

 

Now, this GenericInterface is compatible with any lambda expression that takes one parameter and returns the value of the same type.

// GenericLambda.java
public class GenericLambda {
    public static void main(String[] args) {
        GenericInterface<String> reverse = (str) -> {
            String result = "";
            for (int i = str.length() - 1; i >= 0; i--)
                result += str.charAt(i);

            return result;
        };

        System.out.println("Lambda reversed = " + reverse.func("Lambda"));

        GenericInterface<Integer> factorial = (n) -> {
            int result = 1;
            for (int i = 1; i <= n; i++)
                result = i * result;
            return result;
        };
        System.out.println("factorial of 5 = " + factorial.func(5));
    }
}

 

When you run the program, the output will be:

Lambda reversed = adbmaL
factorial of 5 = 120

 

3. Method Referencing using Lambda

To reference a method using lambda, a new separator double colon added in Java 8 is used. This method reference can be used anywhere in which it is compatible with the functional interface.

Static method reference syntax is:

ClassName::methodName

Reference to the instance method on specific object syntax is:

objRef::methodName

Constructor Reference syntax is:

ClassName::new

Let’s look at code example for static method reference.

// MyInterface.java
@FunctionalInterface
public interface MyInterface {
    int myFunc(int n);
}

// IntOperations.java
public class IntOperations {
    static int factorial(int n) {
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result = i * result;
        }
        return result;
    }
}

// MethodRefMain.java
public class MethodRefMain {

    static int fact(MyInterface myInterface, int n) {
        return myInterface.myFunc(n);
    }

    public static void main(String[] args) {
        // static method referencing
        int result = fact(IntOperations::factorial, 5);
        System.out.println("5 Factorial = " + result);
    }
}

When you run the program, the output will be:

5 Factorial = 120

 

4. Lambdas and Stream API

The new java.util.stream package has been added to JDK8 which allows Java developers to perform operations like filter, map, reduce the collections like List. With the help of Stream API, we can do either parallel or sequential operations over the stream of data. The java.util.stream.Stream interface which is helpful to do bulk operations

The Stream API would allow us to declare either sequential or parallel operation over the stream of data.

import java.util.Arrays;
import java.util.List;

public class StreamMain {

    public static void main(String[] args) {
        List<String> myList = Arrays.asList("Asia:India", "Asia:Nepal", "NorthAmerica:USA", "Africa:Nigeria", "Europe:UK");

        myList.stream()
                .filter(s -> s.startsWith("Asia")) // filter the data
                .map(String::toUpperCase) // map each data
                .sorted()    // sort the data
                .forEach(System.out::println); // print it
    }
}

When you run the program, the output will be:

ASIA:INDIA 
ASIA:NEPAL

 

Starting with Java 8 Streams? Read our article on Introduction to Java 8 Streams.

 

Summary

In this article, we get a basic understanding of Lambda Expressions in Java.We discussed benefits about the Lambda Expressions and what are the different types of Lambda Expressions in Java.

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.

Java 9 New Features

 Java 9 New Features

In this articles, we will be covering Java 9 new features at a high level.We will explore these features along with details as what are the improvements happening to the existing features.

 

Introduction

Java 8 introduced a couple of new and exciting features like lambdas, streams and some of the API changes, Java 9 is coming up with rich feature sets like Jigsaw, Jshell (REPL),  collections and some API changes under the hood.In this, we will explore all Java 9 new features at a high level.You can get detail information of all Java 9 features available JDK 9.

 

1. Modular System – Jigsaw Project 

The modular system is one of the main and defining features of the Java 9.Jigsaw will be responsible for bringing much-needed modularity to the Java platform.One of the main reason to bring modularity to the Java provides modular JVM which can help us to run JVM on different devices with less memory. 

In another way, it’s a mechanism to run only modules and API required by a given application (e.g.application 1 need 3 modules to run completely while application 2 need only 1 module). 

Modules will be defined/ described in a file called module-info.java located at the top of our Java code hierarchy.

In order to understand Java 9 Modular system, let’s take an example of the Order placement process where we need OMS (Order Management System) to place an order but for rest of the use cases (e.g. Browsing site or adding products to the shopping cart), we might not need OMS for our application. We can have a web-based application which allows placing an order, however, we can have other channels which can place an order and we need OMS module to process these orders correctly. To achieve this, we can define 2 modules in Java 9 and can define required dependencies

module com.javadevjournal.shop.order {
    requires com.javadevjournal.erp.oms;
}

Here is a pictorial representation of the Java 9 Module system

Java 9 New Features
Java 9 Modules

Based on the requires statement, JVM will try to determine if it is able to resolve all modules. I strongly believe that Java 9 Modules feature will allow us to structure our application in a better way and will strongly enforce encapsulation and defined/ explicit dependencies.

 

2. JShell (REPL)

Many modern languages provide a tool (Mostly called as REPL or scripting tool) for real-time statement interpretation.One of the benefits of such tool is that you can easily test your code without creating a complete class or project.Java 9 will be introducing REPL or JShell which can be used to quickly run your code and compare results. 

For more details and video tutorial, please read Introduction to Java 9 REPL and JShell

 

3. G1 (Default Garbage Collector)

Java 8 has 4 different Garbage Collector and default Garbage Collector in Java 8 is Parallel / Throughput Collector. G1 will be the new default Garbage Collector in Java 9. G1 was designed for better performance and know to have less number of GC pauses. 

Get more insight of the all available Garbage Collectors and their feature in our other post Java Garbage Collector.

 

 

4. HTTP 2.0 Client

Java 9 is coming up with a new HTTP 2.0 based client which can also be taken as a replacement for the famous.HttpURLConnection Java 9 will be providing full support for new HTTP 2.0 and this new client will be supporting both HTTP/2 protocol and WebSocket.

This new API will be introduced as first incubator module in Java which means it will be introduced as an experimental feature and based on the feedback it will either be added as a full featured module in next release or will be removed from the Java platform.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("www.travellingrants.com")).build();

HttpResponse<String> response = client.send(request,HttpResponse.BodyHandler.asString());

System.out.println(response.statusCode());
System.out.println(response.body());

It’s really easy and clean API, we no longer have to use InputStream or Reader and even our old friend.HttpURLConnection

HTTP 2.0 API also support an Asynchronous call by simply using HttpClient#sendAsync() method instead of HttpClient#send method.There is also option to cancel your request if server support HTTP/2.

 

5. StackWalker API

To put Stack Walk API  in Java 9 in simple words, It provides capabilities to walk through the stack in Java. StackWalker provides a snapshot of the current thread stack trace along with some methods to access it.

Please read our article StackWalker API In Java 9 to get more insight for this new Java 9 feature.

 

6. Process API

Before Java 9 there was a limited support for controlling and managing operating systems processes, even getting hold of simpler OS related process was not a simple one liner solution and require a lot of workarounds.

Java 9 is introducing a lot of improvements to process API for controlling and managing OS related process.

java.lang.ProcessHandle class contains most of the new features of the process API. To get an understanding let’s take an example of getting PID in both Java 8 and Java 9

Java 8
public static void getProcessIdByJava8(){

    try {
        String[] args = new String[] { "/bin/sh", "-c", "echo $PPID" };
        Process p = Runtime.getRuntime().exec(args);
        InputStream p_out = p.getInputStream();
        String s = (new BufferedReader(new InputStreamReader(p_out))).readLine();
        p.destroy();
        if (s != null)
            System.out.println(s);
    } catch (IOException e) {
        e.printStackTrace();
    }
   
}

Java 9
public static void getProcessIdByJava9(){
    System.out.println("Your Process id is :" + ProcessHandle.current().pid());
}

As we saw, getting operating system information using Java 9 process API is quite easy and clean.It gives Java developer an API to interact with the operating system and can be used to get information on the status of the JVM.

We can get a lot of other information from the process API. Read here for more details.

 

7.  Collection Factory Methods

Collection Factory Methods are introduced in Java 9 like Scala. Static methods have been provided by Java 9 on List, Set and Map interfaces which can easily returned unmodifiable collections by calling of() method of the respective interface.

For more detail, please read Collection Factory Methods in Java 9

 

8. Try With Resources Improvement

Java 7 introduced try-with-resources for managing resources automatically and to ensure that resources will be closed after execution of the program.

Before Java 9, in order to use try-with-resources, we will have to use something like this

try (BufferedReader br = new BufferedReader(new FileReader("/input.txt"))) {
    String line;
    while (null != (line = br.readLine())) {
        // processing each line of file
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Or we will be using a very similar syntax, Above syntax provide a lot of features and auto management of the resources, however, we still need to declare a local variable to work with, Java 9 is a further refinement to this feature to avoid verbosity.

 

BufferedReader br = new BufferedReader(new FileReader("/input.txt"));

// Java 9 make it simple
try (br) {
    String line;
    while (null != (line = br.readLine())) {
        // processing each line of file
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

9. Interface Private Method

Java 8 came with certain enhancement while declaring interfaces, few of those features are

  1. Method implementation in interface using default and static methods

However, it still not provide a way to create a private method in Interface. Java 9 will provide a way to have a private method in an interface.This feature will really be useful to avoid redundant code and promote code reusability.

public interface PrivateMethodExample {

    private static String getDBDetails(){
        return "MySQL";
    }

    private boolean checkConnection(String DBDetails){
        return  DBDetails.equalsIgnoreCase("MySQL") ? true : false;
    }

    default void checkDBConnection(){
        String dbName = getDBDetails();
        boolean isAlive =   checkConnection(dbName);  
    }
}

 

10. Мulti-Resolution Image API

Java 9 will be introducing a new API defined under java.awt.image package, it will allow a set of images with different resolutions to be encapsulated into a single multi-resolution image.

For more details read Multi-Resolution Images.

 

 

11. Miscellaneous Java 9 Features

There are other features introduced in Java 9 which I will be covering in another post in more details, here is the list of some of the other features introduced in Java 9

  1. Improvement to Optional API. Read java 8 optional to get a basic understanding of Optional API introduced in Java 8.
  2. Unified JVM Logging.
  3. Stream API Improvement.
  4. Reactive Streams
  5. CompletableFuture API Improvements
  6. Improved Javadoc

 

Summary

In this post, we covered  Java 9 new features. Java 9 is coming up with modular JVM which is going to be one of the defining features of Java 9 along with a number of improvements in the JDK.