Saturday, July 25, 2020

Java 8 - Convert List to Map (Handling Duplicate Keys)

Convert List to Map in Java

1. Introduction


In this article, You'll explore and learn how to convert List to Map in Java 8. 

First, Let us convert List into Map.
Next, Convert List of user-defined(custom) objects to Map and handling with the duplicate keys.
Finally, Sort and collect the Map from List

Java 8 - Convert List to Map (Handling Duplicate Keys)

Tuesday, July 21, 2020

Java String replaceFirst() Example

Java String replaceFirst()

1. Overview


In this String API Methods series, You'll learn replaceFirst() method of String class.

Replaces the first substring of this string that matches the given regular expression with the given replacement.

This method is mostly useful when you want to do the changes only for the first found value and not for all values. But, replace() method replaces for all matches with the given string. You must be careful and choose the right one for your use-case.

Java String replaceFirst() Example

Monday, July 20, 2020

Java String hashCode() example

Java String hashCode()

1. Overview


In this String Methods series, You are going to learn hashcode() method of String class with example programs.

Java String hashCode() method returns the hash code for the String. Hash code value is used in hashing based collections like HashMap, HashTable etc. This method must be overridden in every class which overrides equals() method.

Java String hashCode() example

Thursday, July 16, 2020

Java String codePoints() Example

1. Overview

Java String codePoints()

In this String API Series, You'll learn how to convert String to IntStream with codepoints.

In the new version of java 9, the String class is added with the codePoints() method and returns Stream with integer values.

codePoints() method returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

Java String codePoints()

Java String codePointCount()

1. Overview


In this String API Series, You'll learn how to get the count of the codepoints in the string for a given text range.

In the previous article, we have discussed codePointAt() method which is to get the codepoint at the given index.

codePointCount() returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

Let us jump into codePointCount() method syntax and example programs.

Java String codePointCount()

Wednesday, July 15, 2020

Java String codePointBefore()

1. Overview


In this String Methods series, you'll learn what is codePointBefore() method in String API and with example programs.

2. Java String codePointBefore()


codePointBefore() method returns the character (Unicode code point) before the specified index. The index refers to char values (Unicode code units) and ranges from 1 to length.

If the char value at (index - 1) is in the low-surrogate range, (index - 2) is not negative, and the char value at (index - 2) is in the high-surrogate range, then the supplementary code point value of the surrogate pair is returned. If the char value at index - 1 is an unpaired low-surrogate or a high-surrogate, the surrogate value is returned.

Java String codePointBefore()

Monday, July 13, 2020

Adding/Writing Comments in Java, Comment types with Examples

Adding/Writing Comments in Java:

In this post, We will learn about how to add comments in Java and its significance.

In Java, Comments are allowed to use in addition to the executable declarations and statements i.e. what ever we write code in the class or methods. These are very helpful for better understanding of what code does and not processed by the java compiler. Because, compiler knows it is just comment which is being used for humans understanding (Compiler ignores it). Comments can be written at any part of the class.

More on Core Java

Variable Types
Identifiers and Keywords
Import, Static Import
Packages
Constructor in Java, Types, Examples, Purpose




Adding-Writing Comments in Java




Can write comments before package statement?

Sunday, July 12, 2020

Java Program to Swap Two Numbers

1. Introduction


In this article, You'll learn how to swap two numbers in java. Basically, this can be achieved by using a temporary variable and without using the third variable.

First, let us see how to swap two numbers. This is a basic program for engineering students.

Friday, July 10, 2020

How To Validate Phone Numbers in Java (Regular Expression + Google libphonenumber)

1. Introduction


In this tutorial, We'll learn how to validate phone numbers in java. This is to validate mainly the USA and India country phone numbers but after seeing the example you can develop the validation rules for other countries.

This is a common requirement to verify mobile numbers as we do validation for email address validation but java does not have built-in capability to provide such methods. But, We can achieve this with the help of regular expression and google api with libphonenumber.

Let us jump into writing example programs.

Java 8 Stream Intermediate Operations (Methods) Examples

1. Overview


In this tutorial, We'll learn about What are Intermediate Operations in Java 8 Stream. All these operations are in package java.util.stream.Stream.

In the last tutorial, We've discussed Java 8 Stream API and Lambda Expressions.

Java 8 Stream Intermediate Operations (Methods)

Rules:


Java 8 Stream intermediate operations return another Stream which allows you to call multiple operations in the form of a query.

Stream intermediate operations do not get executed until a terminal operation is invoked.
All Intermediate operations are lazy, so they’re not executed until a result of processing is actually needed.

Traversal of the Stream does not begin until the terminal operation of the pipeline is executed.

Stream Intermediate Operations:

Here is the list of all Stream intermediate operations:
filter()
map()
flatMap()
distinct()
sorted()
peek()
limit()
skip()

Thursday, July 9, 2020

Create Thread without extending Thread and implementing Runnable

1. Introduction


In this quick article, You'll learn how to create a thread without extending the Thread class and implementing the Runnable interface.

Create Thread without extending Thread and implementing Runnable


How to Create Read Only List, Set, Map in Java 8, Java 9 and java 10

1. Introduction


We'll learn what are the ways to create a read only collection List, Set, or Map in java 8 and older versions. In other ways, It is called as Imuutale or unmodifiable collection.

Usually, Whatever the objects that we create using a new keyword will create mutable collections objects as below.

List<String> list = new ArrayList<String>();

Next, On list instance, you can call add() or remove() methods of List interface.

list.add("one");
list.add("two");

list.remove("two");

list.add("three");

System.out.println("List values : "+list);

Output:


List values : [one, three]

You can observe that previously added value "two" is removed from the list and added a new value "three" to it.

Our main core concept of this article is to make the existing list as read only after adding the needed values.

How to Create Read Only List, Set, Map in Java 8, Java 9 and java 10

2. Collections.unmodifiableCollection() Method


The Collections utility class is added with several methods to make the collection as Read Only. All of these are static methods so directly can be accessed with the Collections class.

Collections.unmodifiableCollection() method returns an unmodifiable view of the specified collection. This method works for both list and set examples.

Syntax:


public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)

Collections.unmodifiableCollection() Example:


package com.javaprogramto.readonly;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Collections;

import java.util.List;


public class ReadOnlyCollectionExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();

        list.add("one");

        list.add("two");

        list.add("three");


        list.remove("two");


        System.out.println("List values : " + list);


        Collection<String> readOnlyList = Collections.unmodifiableCollection(list);


        System.out.println("Read only collection : " + readOnlyList);

    }
}


Output:


List values : [one, three]
Read only collection : [one, three]

Now try to add the new value to the readOnlyList. Then, it will produce the runtime exception saying "UnsupportedOperationException".

readOnlyList.add("new value");

Error:


Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at ReadOnlyCollectionExample.main(ReadOnlyCollectionExample.java:25)

3. Collections.unmodifiableList() - To make List as read only


Returns an unmodifiable view of the specified list. Input argument must be a List interface implementation.

package com.javaprogramto.readonly;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class ReadOnlyCollectionunmodifiableListExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();

        list.add("one");

        list.add("two");

        list.add("three");

        list.remove("two");

        System.out.println("List values : " + list);


        List<String> readOnlyList = Collections.unmodifiableList(list);


        System.out.println("Read only collection : " + readOnlyList);


        if (readOnlyList.getClass().getName().contains("Unmodifiable")) {

            System.out.println("readOnlyList is a Read only collections");

        } else {

            System.out.println("This is not Read only collections");

        }

    }
}
Output:
List values : [one, three]
Read only collection : [one, three]
readOnlyList is a Read only collections
Note: Making List as read only can be done in another way using Arrays.asList() method but Arrays class a utility method to only for List and not for Set, Map implementations.


4. Collections.unmodifiableSet() - To make Set as read only


Collections.unmodifiableSet() returns a unmodifiable view for the given set. Input arguemnt must be Set interface implementation and either HashSet or LikedHashSet.
package com.javaprogramto.readonly;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;


public class ReadOnlyCollectionunmodifiableSetExample {

    public static void main(String[] args) {

        Set<String> set = new LinkedHashSet<String>();

        set.add("one");
        set.add("two");
        set.add("three");
       
        set.remove("two");


        System.out.println("Set values : " + set);


        Set<String> readOnlySet = Collections.unmodifiableSet(set);


        System.out.println("Read only collection : " + readOnlySet);


        if (readOnlySet.getClass().getName().contains("Unmodifiable")) {

            System.out.println("readOnlySet is a Read only collections");

        } else {

            System.out.println("readOnlySet not Read only collections");
        }
       
    }
}

Output:
Set values : [one, three]
Read only collection : [one, three]
readOnlySet is a Read only collections

5. Collections.unmodifiableMap() - To make Map as read only


Collections.unmodifiableMap() returns a unmodifiable view for the given Map. Input arguments must be Set interface implementation and either HashMap or LikedHashMap or TreeMap.

package com.javaprogramto.readonly;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class ReadOnlyCollectionunmodifiableMapExample {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<Integer, String>();

        map.put(100, "one");
        map.put(200, "two");
        map.put(300, "three");

        map.remove(100);

        System.out.println("Set map : " + map);


        Map<Integer, String> readOnlyMap = Collections.unmodifiableMap(map);


        System.out.println("Read only map : " + readOnlyMap);


        if (readOnlyMap.getClass().getName().contains("Unmodifiable")) {

            System.out.println("readOnlyMap is a Read only collections");

        } else {

            System.out.println("readOnlyMap not Read only collections");

        }
    }
}
Output:
Set map : {200=two, 300=three}
Read only map : {200=two, 300=three}
readOnlyMap is a Read only collections

6. Java 9 Read Only List


In java 9, It is very easy to do converting an Array into a List as read-only

List interface is added with static method List.of() which takes the varargs.
String[] stringArray = {"1", "2"};

List<String> stringList = List.of(stringArray);

7. Java 10 Read Only List


In java 10 api, List is added with copyOf() and Collectors added with toUnmodifiableList() method.
List.copyOf(list);

List<String> readOnlyListJava10 = list.stream().collect(Collectors.toUnmodifiableList());

Set<String> readOnlySetJava10 = list.stream().collect(Collectors.toUnmodifiableSet());

Map<Integer, String> readOnlyMapJava10 = list.stream().collect(Collectors.toUnmodifiableMap());

8. Conclusion


In this article, You've seen how to make read only Collection classes in Java 10, java 9, and older versions.

As usual, all examples are over GitHub.

Static Method
Collections API
Collections. unmodifiableCollection()
List.copyOf()
List.of()
Collectors.toUnmodifiableList()
GeekForGeeks

Custom HTTP Header with the HttpClient

1. Introduction


In this tutorial, You'll learn today how to set custom HTTP Header to HTTPClient Request. If you want to learn and dig deeper, move to the tutorial section Apache HTTPClient here.

All examples in this post, We will use the domain "http://www.google.com" for creating requests. Because it is considered as always up and running.

Sometimes in the interview, the same is asked as "How to send POST parameters with RequestBuilder?"

Custom HTTP Header with the HttpClient

Adding Partition To Existing Table In Oracle

How do I alter my existing table to create a range partition in Oracle

Creating partition is on a table is very important when you want to see performance improvement especially on DATE columns.
In this post, We will learn how to alter existing table with partition.

How to Create User and Grants in Oracle

What is Partition in Oracle:

Oracle Partitioning allows tables and indexes to be partitioned into smaller, more manageable units, providing database administrators with the ability to pursue a "divide and conquer" approach to data management. ... That table could be range- partitioned so that each partition contains one day of data.

Adding Partition To Existing Table In Oracle

Wednesday, July 8, 2020

Array to List: Program to convert Array to List in Java 8

1. Introduction


In this tutorial, you will learn how to convert an Array to List in java.

An array is a group of same type variables that hold a common name. Array values are accessed by an index that starts from 0. Arrays can hold primitive types and objects based on how the array is defined. If the array is created to store the primitive values then these are stored in the contiguous memory locations whereas objects are stored in the heap memory.

Java.util.List is sub-interface to the Collection interface. List is intended to store the values based on the index and accessed through index only. But, duplicate values can be stored in the list. List interfaces implementations are AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector.

List objects are accessed through the iterator() and listiterator() methods.

Array to List: Program to convert Array to List in Java 8


Let us dive into our core article to convert Array to List and this can be done in the following 4 ways.

  • Native Generics Apparoach
  • Arrays.asList()
  • Collections.addAll
  • Java 8 Stream API - Arrays.stream().collect()
  • Java 8 Stream boxed() for primitive arrays


Read more on How to convert Sting to Arraylist using Arrays.asList().


Input 1 : Array -> {"java", "program", "to.com", "is a ", "java portal"}
Output 1 : List -> {"java", "program", "to.com", "is a ", "java portal"}

Input 2 : Array -> {10, 20, 30, 40, 50}
Output 2 : List -> {10, 20, 30, 40, 50}


All Examples :


 // 1. Example on Arrays.asList()
 List<T> outputList = Arrays.asList(array);

  // 2. Example on Collections.addAll()
  Collections.addAll(outputList, array);
 
  // 3. Example on Arrays.stream().collect()
  List<T> outputList = Arrays.stream(array).collect(Collectors.toList());
 
  // 4. Example on boxed() method for primitive int array
  List<Integer> outputList = Arrays.stream(array).boxed().collect(Collectors.toList());

2. Convert List to Array using Native Generic Approach


package com.javaprogramto.java8.arraytolist;

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

public class ArrayToListExample {

    public static void main(String[] args) {

        String[] intArray = {"10", "20", "30", "40", "50"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("COnverted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();
        for (T t : array) {

            outputList.add(t);

        }

        return outputList;
    }

}

Output:
Array : [10, 20, 30, 40, 50]
COnverted ArrayList : [10, 20, 30, 40, 50]

3. Convert List to Array Using Arrays.asList()


Arrays class has a utility static method asList() which takes an array as input and returns a list object with array values.

package com.javaprogramto.java8.arraytolist;

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

public class ArrayToListAsListExample {
    public static void main(String[] args) {

        String[] intArray = {"java", "program", "to.com", "is a ", "java portal"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();

        outputList = Arrays.asList(array);
        return outputList;
    }

}


Output:
Array : [java, program, to.com, is a , java portal]
Converted ArrayList : [java, program, to.com, is a , java portal]

4. Convert List to Array Using Collections.addAll()


Collections class has a utility static method addAll() which takes two parameters. The first argument is the Output List and the second argument is the array of values. This method converts the second argument array to List. It populates the values from array to the given output list.

package com.javaprogramto.java8.arraytolist;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayToListCollectionsAddAllExample {
    public static void main(String[] args) {

// Example using Collections.addAll(outputList, array);

        String[] intArray = {"java", "program", "to.com", "is a ", "java portal"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

        List<T> outputList = new ArrayList<T>();

        Collections.addAll(outputList, array);

        return outputList;
    }

}

Output:
Array : [java, program, to.com, is a , java portal]
Converted ArrayList : [java, program, to.com, is a , java portal]

5. Java 8 Convert Array to List using Arrays.stream().collect()


Java 8 Stream API has added with a stream() method in the Arrays class to provide arrays support to Streams.

First, Convert the array into Stream by using Arrays.stream()
Second, Convert Stream into list using Collectors.toList() method.
Finally, Collect the converted stream into list using stream.collect() method.


package com.javaprogramto.java8.arraytolist;

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

public class ArrayToListJava8Stream {
    public static void main(String[] args) {

// Example using Collections.addAll(outputList, array);

        String[] intArray = {"java", "program", "to", "convert", "array to list"};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<String> list = convertArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static <T> List<T> convertArrayToList(T[] array) {

// convert array to stream
        Stream<T> stream = Arrays.stream(array);

// collecting converted stream into list
        List<T> outputList = stream.collect(Collectors.toList());

        return outputList;
    }

}


Output:
Array : [java, program, to, convert, array to list]
Converted ArrayList : [java, program, to, convert, array to list]

6. Java 8 Convert Primitive Array to List using boxed() method


Stream api is added with boxed() method to work with primitive collections such as int[], float[] and double[] arrays.

boxed() method converts primitive values to its wrapper objects.

package com.javaprogramto.java8.arraytolist;

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

public class ArrayToListJava8Boxed {
    public static void main(String[] args) {

// Example using stream.boxed()

        int[] intArray = {1, 2, 3, 4, 5, 6, 6};
        System.out.println("Array : " + Arrays.toString(intArray));

        List<Integer> list = convertPrimitiveArrayToList(intArray);

        System.out.println("Converted ArrayList : " + list);

    }

    private static List<Integer> convertPrimitiveArrayToList(int[] array) {

// convert int array to Integer stream with boxed() method
        Stream<Integer> stream = Arrays.stream(array).boxed();

// collecting converted stream into list
        List<Integer> outputList = stream.collect(Collectors.toList());

        return outputList;
    }

}
Output:
Array : [1, 2, 3, 4, 5, 6, 6]
Converted ArrayList : [1, 2, 3, 4, 5, 6, 6]

7. Conclusion


In this article, you've seen all possible ways in the Java traditional and java 8 stream api.

Monday, July 6, 2020

@EnableAutoConfiguration Annotation in Spring Boot

Spring Boot @EnableAutoConfiguration

1. Introduction


In this article, We'll be learning how to use @EnableAutoConfiguration annotation in spring boot.

@EnableAutoConfiguration is an interface as part of org.springframework.boot.autoconfigure package.

@EnableAutoConfiguration Annotation in Spring Boot


How to install Java 8 on Mac? Installing Java 8 on Latest Mac OS X (HomeBrew Guide)

1. Introduction


In this tutorial, You'll be learning how to install Java 8 or the latest versions of java in Mac OS.
If you have got the new mac book then you are existed to install java.

This is a very easy process and will show you step by step in an easy manner.

First, let us start with the Manual Installation and next go with the HomeBrew approach which is simpler managed automatically with few commands.

Before that download the latest java from Oracle or OpenJDK official websites.

Read more on Why Java is preferred?

How to install Java 8 on Mac? Installing Java 8 on Latest Mac OS X (HomeBrew Guide)


2. Manual Installation of java 8 or Higher Versions


Let us go through the manual installation of Java 14 or 8. To run the following you would need the admin access.

2.1 Download the latest JDK or needed version for you.

2.2 Copy the tar file to the location "/Library/Java/JavaVirtualMachines"
$ cd /Library/Java/JavaVirtualMachines

$ pwd
/Library/Java/JavaVirtualMachines

$ sudo cp ~/Downloads/openjdk-14_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines

$ pwd
/Library/Java/JavaVirtualMachines

2.3 Extract the contents here.
$ sudo tar xzf openjdk-14_osx-x64_bin.tar.gz
2.4 Delete the tarfile if you no need to keep the backup.
$ sudo rm openjdk-14_osx-x64_bin.tar.gz
2.5 Find the java version installed
$ /usr/libexec/java_home -v14

/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home
2.6 Add the java home path to the ".bash_profile" file.
open the file with the VI editor. Enter into edit mode by pressing 'i' and then add the below line. Press :wq to save and come out of VI editor.
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home
2.7 Source bash_priofile file
$ source ~/.bash_profile
2.8 Test the version installed on mac properly or not using "java --version".
$ java -version
openjdk version "14" 2020-03-17
OpenJDK Runtime Environment (build 14+36-1461)
OpenJDK 64-Bit Server VM (build 14+36-1461, mixed mode, sharing)
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home

3. Installing java 8 using HomeBrew

HomeBrew provides simpler way to install and manage the software and tools required on mac without any manual intervention.
If you are new then please see the article on HomeBrew installation and  Commands shown in the previous article.

3.1 Install Homebrew or update it if you have already on mac.
The update will take some time if you have done it a long time ago.

$ brew update
==> Downloading https://homebrew.bintray.com/bottles-portable-ruby/portable-ruby-2.6.3_2.yosemite.bottle.tar.gz
################################################################################################################################################################ 100.0%
3.2 Add open jdk to the brew

By default, all repositories are not added to the brew. So, to add the additional repos you need to use the brew tap command.

$ brew tap adoptopenjdk/openjdk
Updating Homebrew...
3.3 Find all JDK versions are on Brew
$ brew search jdk
==> Formulae
openjdk                                                                           openjdk@11
==> Casks
adoptopenjdk                     adoptopenjdk12                   adoptopenjdk13-openj9            adoptopenjdk14-openj9-jre-large  adoptopenjdk9
adoptopenjdk10                   adoptopenjdk12-jre               adoptopenjdk13-openj9-jre        adoptopenjdk14-openj9-large      jdk-mission-control
adoptopenjdk11                   adoptopenjdk12-openj9            adoptopenjdk13-openj9-jre-large  adoptopenjdk8                    oracle-jdk
adoptopenjdk11-jre               adoptopenjdk12-openj9-jre        adoptopenjdk13-openj9-large      adoptopenjdk8-jre                oracle-jdk-javadoc
adoptopenjdk11-openj9            adoptopenjdk12-openj9-jre-large  adoptopenjdk14                   adoptopenjdk8-openj9             sapmachine-jdk
adoptopenjdk11-openj9-jre        adoptopenjdk12-openj9-large      adoptopenjdk14-jre               adoptopenjdk8-openj9-jre
adoptopenjdk11-openj9-jre-large  adoptopenjdk13                   adoptopenjdk14-openj9            adoptopenjdk8-openj9-jre-large
adoptopenjdk11-openj9-large      adoptopenjdk13-jre               adoptopenjdk14-openj9-jre        adoptopenjdk8-openj9-large
Venkateshs-MacBook-Pro-2:JavaVirtualMachines venkateshn$ 
It is showing with a blue tick for version 11. That means, My machine is already having the java 11 version.

3.4 Choose the right version and run one of the following commands.

brew cask install adoptopenjdk8
brew cask install adoptopenjdk9
brew cask install adoptopenjdk10
brew cask install adoptopenjdk11
brew cask install adoptopenjdk12
brew cask install adoptopenjdk13
brew cask install adoptopenjdk14

3.5 install JDK 14 version

This will take quite some time based on your internet speed.
$ brew cask install adoptopenjdk14
Updating Homebrew...
==> Downloading https://github.com/AdoptOpenJDK/openjdk14-binaries/releases/download/jdk-14.0.1%2B7/OpenJDK14U-jdk_x64_mac_hotspot_14.0.1_7.pkg
==> Downloading from https://github-production-release-asset-2e65be.s3.amazonaws.com/233878254/64ac0f80-830e-11ea-8bcd-a9f8ee45c527?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-
######################################################################## 100.0%
==> Verifying SHA-256 checksum for Cask 'adoptopenjdk14'.
==> Installing Cask adoptopenjdk14
==> Running installer for adoptopenjdk14; your password may be necessary.
==> Package installers may write to any location; options such as --appdir are ignored.
Password:
installer: Package name is AdoptOpenJDK
installer: Upgrading at base path /
installer: The upgrade was successful.
package-id: net.adoptopenjdk.14.jdk
version: 14.0.1+7
volume: /
location: Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk
install-time: 1593938817
🍺  adoptopenjdk14 was successfully installed!
3.6 How to see the installed Java location?
Run from terminal "/usr/libexec/java_home -V" command which shows all java versions installed on this machine already.
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (6):
    14.0.1, x86_64: "AdoptOpenJDK 14" /Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
    12.0.1, x86_64: "Java SE 12.0.1" /Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home
    11.0.7, x86_64: "Java SE 11.0.7" /Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home
    1.8.0_252, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
    1.8.0_251, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home
    1.8.0_161, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_161.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
3.7 Verify the java version
$ java --version
openjdk 11.0.7 2020-04-14
OpenJDK Runtime Environment (build 11.0.7+10)
OpenJDK 64-Bit Server VM (build 11.0.7+10, mixed mode)
Currently, I have set JAVA_HOME to java 11 version. Because of this, we are seeing the java 11 version even though installed the latest java 14.
That's all. The latest version is installed.

4. How to change or Switching between Java versions

In the above sections, We've already shown you how to install the different versions of java using HomeBrew and Manual installation steps.

If you have installed any version of java and there are some cases you need to change the java version based on your project needs.

Note: In the market, there is a tool jenv.be to switch between the java versions but I prefer to use Export JAVA_HOME in .bash_profile file.

4.1 First, let us see how to see the installed versions of java.

Open the terminal and hit the "/usr/libexec/java_home -V" command and this shows all versions installed with locations.
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (6):
    14.0.1, x86_64: "AdoptOpenJDK 14" /Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
    12.0.1, x86_64: "Java SE 12.0.1" /Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home
    11.0.7, x86_64: "Java SE 11.0.7" /Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home
    1.8.0_252, x86_64: "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
    1.8.0_251, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home
    1.8.0_161, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_161.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/adoptopenjdk-14.jdk/Contents/Home
4.2 Open the .bash_profile file

$ vim ~/.bash_profile

Add the following to the .bash_profile file
export JAVA_HOME_8=$(/usr/libexec/java_home -v1.8)
export JAVA_HOME_11=$(/usr/libexec/java_home -v11)
export JAVA_HOME_14=$(/usr/libexec/java_home -v14)

# Java 8
export JAVA_HOME=$JAVA_HOME_8

# Java 11
# export JAVA_HOME=$JAVA_HOME_11
Save the file and come out of VI editor.

4.3 Based on the above change, we are setting JAVA_HOME to java 1.8 version.

4.4 Reload the .bash_profile
$ source ~/.bash_profile
4.5 Verify the java version
$ java -version

openjdk version "1.8.0_251"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_251-b08)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.251-b08, mixed mode)

5. Conclusion

In this article, You have seen how to install Java on Mac OS with manual and HomeBrew Installation with step by step.

As well as seen how to change the java version as you needed from the terminal with few commands.



Ref

Oracle java 8 steps

Open JDK

HomeBrew Commands

jenv.be

How to change the Java version on Mac OS

Sunday, July 5, 2020

Stream anyMatch() Method in Java 8 to find the value in the Collection or Stream

1. Introduction


In this article,  You'll be learning how to use the new java 8 Stream API method anyMatch() with Examples.

anyMatch(): This method returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. 

This is a short circuit terminal operation.

Java 8 Stream anyMatch() Method to find the value in the Collection or Stream

Java 8 Stream anyMatch() Examples

Saturday, July 4, 2020

HomeBrew in Mac? How it simplifies Installation process with commands?

1. Introduction


In this tutorial, you will learn what is HomeBrew in Mac os and what is the list of commands of Homebrew and how it simplifies the installation process of software.

2. What is homebrew in Mac?


Homebrew is a free and open-source software package management system that simplifies the installation of software on Apple's macOS operating system and Linux. The name is intended to suggest the idea of building software on the Mac depending on the user's taste that's why it was named HomeBrew.

Java 8 Program To Check if a value is present in an Array - Stream anyMatch() Example

1. Introduction


In this tutorial, We'll be learning how to check whether a value is present in the array using linear and Binary search.

Next, using java methods such as contains() and Stream API anyMatch() method with primitive and String values.

Java 8 Program To Check if a value is present in an Array


Examples:

Input: arr[] = [6, 7, 10, 5, 70, 9], input 5
Output: true

Input: arr[] = [0, 8, -9, 56, 8], input = -5
Output: false

Java Program to Add Two Binary Numbers

1. Introduction


In this tutorial, You will learn a java program on how to add two binary numbers in binary format. Binary numbers are represented in only '0' and '1's. This is not having any other numbers. If a number has digits apart from 0 and 1 it is not a binary number. I have seen many examples on the internet all are showing only programs but giving the explanation. Here it is different than the Bitwise AND operator. It looks like & operator but not. You will get clarified in this article. Do not skip any content and also do not see the code directly.

Java Program to Add Two Binary Numbers


We have already discussed in previous articles on how to add two numbers in java. This is a very basic program but a common interview question. To make this complicated interviewer will ask to do not use + operator to make the sum of two numbers.

How to create a thread without implementing the Runnable interface in Java?

1. Introduction


In this tutorial, You'll learn how to create a thread without implementing the Runnable interface in Java.

Thread is a lightweight process and every program in java starts in a thread. So by default when you run the main program that has the main() method, JVM will create a thread to run the main program. The default thread is called "main thread".

Additionally, Java supports multithreading which means you can one or more threads at the same time.

Let us see the different ways to create a thread in java using Anonymous implementation for the Runnable interface.

How to create a thread without implementing the Runnable interface in Java?


Wednesday, July 1, 2020

Java 8 Stream – How to Read a file line by line

1. Introduction


In this article, You'll learn how to read a file line by line using Java 8 Streams new API methods from Files, BufferedReader lines() methods.

We have already discussed how to read the large files efficiently in java with Streams.

Java 8 Stream – How to Read a file line by line