الثلاثاء، 26 يناير 2021

Java TreeMap Vs HashMap With Examples

1. Overview

In this tutorial, We will learn the core differences between TreeMap and HashMap classes with example programs.

If you are new to java programming, suggest to go through the below topics.

HashMap Examples

TreeMap Examples

In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.

Java TreeMap Vs HashMap With Examples


HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.

2. Similarities between HashMap and TreeMap

The below are the common things in both classes. Let us look into those before understanding the differences.

2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.

2.2 Both stores the values based on the keys. Always key and value should be provided.

2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.

2.4 These are not synchronized.

2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.

3. HashMap Examples

In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.

Further tried to print the values using iterator and deleted the key "0333" from the original hashmap.

Removal key from hashmap produces the runtime exception.

package com.javaprogramto.collections.hashmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExamples {

	public static void main(String[] args) {

		Map<String, String> hashMap = new HashMap<>();

		hashMap.put("0111", "one's");
		hashMap.put("0222", "two's");
		hashMap.put("0333", "three's");
		hashMap.put("0444", "four's");
		hashMap.put("0111", "one's modified");

		System.out.println("HashMap values are - " + hashMap);

		System.out.println("Iterating Hashmap and modifying the values");

		Set<String> keys = hashMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + hashMap.get(key));
			if (key == "0333") {
				hashMap.remove(key);
			}
		}

	}

}


Output:


HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating Hashmap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
	at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)


4. TreeMap Examples

In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.

Further tried to print the values using iterator and deleted the key "0333" from the original treemap.

Removal key from treemap produces the runtime exception.

package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExamples {

	public static void main(String[] args) {

		Map<String, String> treeMap = new TreeMap<>();

		treeMap.put("0111", "one's");
		treeMap.put("0222", "two's");
		treeMap.put("0333", "three's");
		treeMap.put("0444", "four's");
		treeMap.put("0111", "one's modified");

		System.out.println("treeMap values are - " + treeMap);

		System.out.println("Iterating treeMap and modifying the values");

		Set<String> keys = treeMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + treeMap.get(key));
			if (key == "0333") {
				treeMap.remove(key);
			}
		}

	}
}


Output:


treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating treeMap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
	at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)
	at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)

5. Differences between HashMap and TreeMap

The below are the main differences between these two maps.

5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.

5.2 HashMap is implemented based on the hashtable

     TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.

5.3 HashMap allows only one null key and multiple null values.

      TreeMap does not allow null key but allows null values.

5.4 HashMap does not sort the keys where as TreeMap does sort the keys.

5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.

5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.

6. Conclusion

In this article, We've seen the first example programs on HashMap and TreeMap classes and next similarities and differences between HashMap and TreeMap.

GitHub HashMap

GitHub TreeMap

Java 8 Stream map() and filter() methods

Java Arrays.setAll() Examples To Modify Existing Array

1. Overview

In this article, You'll learn how to use JDK 1.8 Arrays.setAll() method to modify the existing values of the array with a unique generator function. Arrays class is part of java.util package.

This method sets all elements of the specified array, using the provided generator function to compute each element.

In the previous article, We've seen how to set the whole array with the same value using Arrays.fill() method?

Java Arrays.setAll() Examples

السبت، 23 يناير 2021

Java LocalDate atStartOfDay() Example

1. Overview

In this tutorial, We'll learn how to use LocalDate.atStartOfDay() method in java 8. This is the newly added method in Date Time API in java 8.

atStartOfDay() method does appends the might night date with time part as 00:00 to LocalDate.

This is an overloaded method and available in two versions as below. 

public LocalDateTime atStartOfDay()

public ZonedDateTime atStartOfDay(ZoneId zone)


public LocalDateTime atStartOfDay(): This method appends the mid night to the LocalDate and returns it as LocalDateTime object with time default values as zero's.

public ZonedDateTime atStartOfDay(ZoneId zone): This method takes ZoneId instance for time zone value and converts the LocalDate to ZonedDateTime by adding the time part as zero's.

Let us explore the examples on these two methods with examples.

Java LocalDate atStartOfDay() Example



But, you need to remember one core point is that LocalDate does not store the time part but to convert it to LocalDateTime, we need to add time part. This adding the time part is done with atStartOfDay() method.


2. Java 8 LocalDate.atStartOfDay() - LocalDate to LocalDateTime


Understand the example program using atStartOfDay() method with zero parameters to convert localdate to LocalDateTime object to mid night and adding time units with default values as 0.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Example for public LocalDateTime atStartOfDay() method in LocalDate class in
 * java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayExamples {

	public static void main(String[] args) {
		// Example 1

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime1 = localDate1.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDateTime1 : " + localDateTime1);

		// Example 2

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime2 = localDate2.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("localDateTime2 : " + localDateTime2);
	}
}

Output:
localDate1 : 2020-12-07
localDateTime1 : 2020-12-07T00:00
localDate2 : 2023-02-02
localDateTime2 : 2023-02-02T00:00

3. Java 8 LocalDate.atStartOfDay(ZoneId z) - LocalDate to ZonedDateTime


Next, example on how to convert LocalDate to ZonedLocalDate in java 8 with atStartOfDay() method that takes ZoneId as argument.

This method also works by adding time units as zero but it converts the date part as per the given timezone id.

In the below example, we have tried with the system timezone, Singapore and EST time zone dates.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example for public ZonedDateTime atStartOfDay(ZoneId zoneid) method in
 * LocalDate class in java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayZoneIdExamples {

	public static void main(String[] args) {
		// Example 1 - IST

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// Getting the default timezone from system.
		ZoneId defaultId = ZoneId.systemDefault();

		// converting LocalDate object to ZonedDateTime object using timezone.
		ZonedDateTime zonedDateTime1 = localDate1.atStartOfDay(defaultId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("zonedDateTime1 : " + zonedDateTime1);

		// Example 2 - EST

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// Getting the EST timezone from system.
		ZoneId timezoneESTId = ZoneId.of("US/Eastern");

		// converting LocalDate object to ZonedDateTime object using est zone id;
		ZonedDateTime zonedDateTime2 = localDate2.atStartOfDay(timezoneESTId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("zonedDateTime2 : " + zonedDateTime2);

		// Example 2 - Singapore

		// creating LocalDate object
		LocalDate localDate3 = LocalDate.of(2023, 02, 02);

		// Getting the Asia/Singapore timezone from system.
		ZoneId timezoneSingaporeId = ZoneId.of("Asia/Singapore");

		// converting LocalDate object to ZonedDateTime object using Asia/Singapore zone id;
		ZonedDateTime zonedDateTime3 = localDate3.atStartOfDay(timezoneSingaporeId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate3 : " + localDate3);
		System.out.println("zonedDateTime3 : " + zonedDateTime3);
	}
}
Output:
localDate1 : 2020-12-07
zonedDateTime1 : 2020-12-07T00:00+05:30[Asia/Kolkata]
localDate2 : 2023-02-02
zonedDateTime2 : 2023-02-02T00:00-05:00[US/Eastern]
localDate3 : 2023-02-02
zonedDateTime3 : 2023-02-02T00:00+08:00[Asia/Singapore]
From the output, We can see that timezone is added in the returned ZonedDateTime object and time units are 00:00 values.


4. Conclusion


In this article, we've seen how to use LocalDate.atStartOfDay() method with examples to convert LocalDate object to LocalDateTime and ZoneDateTime objects in java 8.


الجمعة، 22 يناير 2021

How To Iterate or Traverse TreeMap In Reverse Order in Java?

1. Overview

In this tutorial, We will learn how to traverse and print the values of the TreeMap in the reverse order in java?

By default, TreeMap sorts the objects added to it in ascending order. But, now we want to print the values are in reverse order that means in the descending order. 

In the previous article, we have seen how to traverse TreeMap in natural order in java 8?

This can be done using the following in 3 ways.

1) Collections.reverseOrder()
2) TreeMap.descendingkeySet()
3) TreeMap.descendingMap()

How To Iterate or Traverse TreaMap In Reverse Order in Java?


2. TreeMap Reverse Traverse - Collections.reverseOrder()


First, let us learn the simple and easy one to understand the reversing and accessing the values from TreeMap.

When we create the TreeMap object, we just need to pass the Collections.reverseOrder() to the TreeMap constructor. Collections.reverseOrder() method indicates to TreeMap sort the keys based on the reverse order that is descending order.

The below example is based on the Collections.reverseOrder() method.

package com.javaprogramto.collections.treemap;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReverseTraversalExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with reverse comparator using Collections.reverseOrder()
		Map<String, Integer> studentsCountMap = new TreeMap<>(Collections.reverseOrder());
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method which returns the keys in the reverse order
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:

See how the order of the output is printed in the reverse order.

Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

3. TreeMap Reverse Traverse - Collections. descendingkeySet()


The above method works only when we have control over creating the TreeMap instance otherwise need to follow the new method as below.

There are some scenarios where the TreeMap is created by another api or library that TreeMap object you are getting into your code.

In such cases, TreeMap has another method descendingkeySet() to get the keys in the descending order which is contrary to the natural order.

But, First need to get the keys in descending order and next get the value from map again with get() method.
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReversedescendingkeySetExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting all keys as Set object using descendingKeySet()
		Set<String> keysSet = studentsCountMap.descendingKeySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:
Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

4. TreeMap Reverse Traverse - Collections. descendingMap()


Finally, TreeMap has another useful method to get the Map in descending order with descendingMap().

Next, iterate returned map with java 8 forEach() method to print the key-values

import java.util.Map;
import java.util.TreeMap;

public class TreeMapReversedescendingkeymapExample {

	public static void main(String[] args) {

		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Getting all keys as Set object using descendingKeySet()
		Map<String, Integer> map = studentsCountMap.descendingMap();

		map.forEach((key, value) -> System.out.println("Key - " + key + ", Value - " + value));
	}
}

5. Conclusion


In this article, we have explored the different ways to traverse the TreeMap in the reverse order.


الأربعاء، 20 يناير 2021

How To Iterate TreeMap in older Java and new Java 8? Or How to iterate over each entry in a Java Map?

1. Overview

In this tutorial, We will learn how to iterate the map in older java versions and examples in java 8.

And alos let us explore how to iterate the keys of TreeMap sorted that means in the ascending order.

TreeMap can be used where we want the map sorted based on the key by default in the ascending or descending order use cases.

java 8 TreeMap Iterate Examples


2. Example to Iterate the TreeMap before JDK 8


In the below code we have created the TreeMap object and added few key value pairs. Here key is the type String and Value is type of Integer.


package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapIterate {

	public static void main(String[] args) {
		
		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}

	}

}

Output:

Key - 1nd class, Value - 100
Key - 2nd class, Value - 200
Key - 3nd class, Value - 300
Key - 4nd class, Value - 400
Key - 5nd class, Value - 500

In the above program, we have first got the all the keys of treemap using keySet() method and next used the iterator() method to get the Iterator instance.

Finally, used the traditional iterate method workflow to get the each key from iterator and passed the key to treemap to get the value of the corresponding key.

3. Java 8 Lamdba Foreach TreeMap


Next, Look at the below program to get the keys and values of TreeMap using Java 8 Lambda expressions with forEach() method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Java 8 lambda foreach
		studentsCountMap.forEach((key, value) -> {
			System.out.println("Key - " + key + ", Value - " + value);
		});
	}
}

This ways also produces the same output as seen in the above section. This is the simplified version in java 8 and it internally uses the BiConsumer functional interface.


4. Java 8 Stream Foreach TreeMap EntrySet


Finally, explore the java 8 stream construct to get the Entry object from stream and pass it to forEach method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// java 8 Stream entry forEach
		studentsCountMap.entrySet().stream().forEach(
				entry -> System.out.println("entry key - " + entry.getKey() + ", entry value - " + entry.getValue()));
	}
}


Output:
entry key - 1nd class, entry value - 100
entry key - 2nd class, entry value - 200
entry key - 3nd class, entry value - 300
entry key - 4nd class, entry value - 400
entry key - 5nd class, entry value - 500

5. Conclusion


In this article, We have seen how to iterate the TreeMap in older and new JDK versions with examples.





الخميس، 7 يناير 2021

How To Convert String to Float in Kotlin?

1. Overview

In this tutorial, We will learn how to convert the String value to Float in Kotlin. This conversion is done using toFloat() method of String class.

But there are many cases where it gives parsing errors for wrong inputs.

How To Convert String to Float in Kotlin?


2. Kotlin String to Float using toFloat() Method

Converting string to float is done with toFloat() method of string class.

toFloat() method is to parse the String value into Float. If the string is not a valid form of a number or any non-number presents then it throws NumberFormatException.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String<) {

    var str : String = "12345.678"
    var float1 : Float = str.toFloat();
    println("string to float - float1 $float1")

    var str2 : String = "A123"
    var float2 : Float = str2.toFloat();
    println("string to float - float2 $float2")
    
}


Output:


string to float - float1 12345.678
Exception in thread "main" java.lang.NumberFormatException: For input string: "A123"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.base/java.lang.Float.parseFloat(Float.java:461)
	at com.javaprogramto.kotlin.conversions.StringToFloatExampleKt.main(StringToFloatExample.kt:10)


3. Kotlin String to Float using toFloatOrNull() Method

Next, use the another method for string to float conversion if the input string is not a valid number.

Call toFloatOrNull() method to get the null value if the string is having at least one non-digit.

Method toFloatOrNull() will convert String to Float.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String>) {

    var str : String = "456.75F"
    var float3 = str.toFloatOrNull();
    println("string to float - float3 $float3")

    var str2 : String = "PI3.14"
    var float4 = str2.toFloatOrNull();
    println("string to float - float4 $float4")
}


Output:

string to float - float3 456.75
string to float - float4 null


Note: When you are calling the toFloatOrNull() method, you should not specify the type to hold the value like var float3 : Float = str.toFloatOrNull(). This will give the compile error "Kotlin: Type mismatch: inferred type is Float? but Float was expected"


4. Conclusion

In this article, We've seen how to convert the string values into Float in Kotlin. And also how to handle if the string is containing the characters other than numbers.

GitHub

Kotlin Ternary Operator


الأربعاء، 6 يناير 2021

Kotlin Variables and Basic Types With Examples - Kotlin Tutorial

1. Overview

In this tutorial, We will learn how to create the variables in Koltin for basic types using var.

var is a keyword in kotlin which is used to declare the any type of variable.

Kotlin has another keyword "val" to declare the variables.

Any variable is declared using var that value can be changed at anytime whereas variable declared with val keyword value can not modified one it is initialized.

Mainly val is used to define the constants in kotlin.

Kotlin Variables and Basic Types



2. Variable var examples


var keyword is used in the variable declaration. When you are using var keyword, that indicates the value can be changed at any time and the variable type is optional. If we are not provided the type then it takes the type implicitly based on the value assigned.

Syntax:

var <variable-name> : <variable-type-optional> = value;

Examples:

Below are the few examples on with and without variable type.

First created a double variable with var keyword with 3.14 value. Next used only var and did not mention any type but assigned the value. So it takes it as double internally because value is double type.

Additionally, created a variable with string content and not mentioned its type. But, kotlin has the intelligence to inspect the value and assign the right type.

if you call the welcome.toUpperCase() method, it does not throw any error. because it knows that object is type of String. So, We can use all methods from String class.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // double type
    var pi : Double = 3.14
    println("Double PI value $pi")

    // without type but it takes the double type internally based on the value
    var doubleValue = 3.14;
    println("Default type double $doubleValue")

    // Without type but it takes as String type from assigned value
    var welcome = "hello world"
    println("string welcome note $welcome")

    var str : String = "i am string"
    println("string type note $str")
}

Output:
Double PI value 3.14
Default type double : doubleValue
string welcome note hello world
string type note i am string

3. val Variable Examples


val is an another keyword in koltin and it is alos used to declare the variables.

Let us create a variable and try to change the value to new one using var and val variables.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // int type varaible with var keyword
    var number: Int = 12345;
    println("old value of number : $number")
    number = 10000
    println("new value of number : $number")

    // int type variable with val keyword
    val highestMark: Int = 99;
    println("old value of highestMark : $number")
    highestMark = 98
    println("new value of highestMark : $number")
}


Output:
Kotlin: Val cannot be reassigned

It will produce the compile time error saying value can not be reassigned for val type variable.

So, val keyword is only to declare the constant values because it will not allow to change the value.

4. Difference between var and val


The main difference between the val and var keywords - is var type variables values can be modified and reassigned with the new values but val type variables can not be reassigned with the new values.

5. Assigning the large numbers to variables


When you are using the kotlin in the real time applications, there will be a need to hold the credit card or debit card numbers and phone numbers. 

var creditCardNumber : Long = 4320123456782468;

The above number is not readable but it holds the actual value. To make the numbers more readable, we can use the underscore(_) delimiter in between the numbers.

We can use the underscore for any numbers even it is good to use for currency values or time values.

but when you print or use for different operations, it does not print or get error because of underscore usage. It removes the underscore while performing any mathematical operations. This delimiter just makes the data readable form.

Look the below example for better understanding.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {
    // long numbers with underscore for readable

    var creditCardNumber: Long = 4320_3456_9808_4389
    var debitCardNumber = 1234_45678_1234_9876L
    var timeInMilliSeconds = 60_000

    // printing
    println("Credit card number : $creditCardNumber")
    println("Debit card number : $debitCardNumber")
    println("Time in milli seconds : $timeInMilliSeconds")
}

Output:

Credit card number : 4320345698084389
Debit card number : 12344567812349876
Time in milli seconds : 60000

6. Kotlin Variable With Null Values - Null Safe (?)


As of now, we have seen the variable declaration and its initialization in single line. But now you want to do only the declaration with null value.

Now, how can we create a variable with null value in kotlin?

Use the ? symbol at the end of the variable declaration to assign with null value. Look at the below syntax.

val/var <variable-name> : <variable-type-optional> ?;

Sample example program to show variable nullable.

 // declaring a variable with the null
 val noValue : String?

 // assigning value
 noValue = "assigned value"

 // printing the value
 println("novalue is now : $noValue")

Output:

novalue is now : assigned value


Note: We can not use the null variable without initializing to a value. It show the compile time error "Kotlin: Variable 'noValue' must be initialized"

7. Type Conversions


Next, let us focus on the type conversions in kotlin.

We will try to convert Int to Long value without any casting. Just assign the Int variable to Long variable.

var number1 : Int = 10;
var number2 : Long = 12345678;

// compile time error : Kotlin: Type mismatch: inferred type is Int but Long was expected
// number2 = number1;

// right conversion
number2 = number1.toLong();
println("number 2 : $number2")

Output:

number 2 : 10

In the above program first directly assigned the int value to the long value but it give compile time error.

Kotlin does not support the direct assignment conversions when the type is mentioned in the declaration. Use toLong() method to do the explicit conversion from Int to Long. This is the process to convert from any type to any type in kotlin.

If the type is not mentioned in the declaration then it is allowed for direct assignment conversion.

var number3 = 10;
var number4= 12345678;

// no compile time error
 number4 = number3;

println("number4 : $number4")

Output:

number4 : 10

Type conversion with nullable type:

When you are using the nullable value type (?) in the declaration then you must use always the variable usage.

Use the null safe(?) operator when calling methods on the variable otherwise will get the compile time error.

// variable with null type and value assignment
var number5 : Int? = 100
var number6 : Long? = 200

// compile time error - Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?
// number6 = number5.toLong()

// no error with null safe
number6 = number5?.toLong();

println("number 6 : $number6")

Output:

number 6 : 100

8. Kotlin Basic Types 


Kotlin has the basic type supports as similar to the Java.

  • Numbers
                Byte
                Short
                Int
                Long
                Float
                Double
  • Char
  • Boolean
  • Array

let us explore the different examples on how to create the numbers, characters, booleans and arrays type variables in kotlin.

// Numbers
// Byte : range -128 to 127
var byteVar: Byte = 100
println("Byte variable : $byteVar")

// Short : range -32768 to 32767
var shortVar: Short = -1000
println("Short variable : $shortVar")

// Int : range -2^31 to 2^31-1
var intVar: Int = 12345
println("Int variable : $intVar")

// Long : range -2^63 to 2^63-1
var longVar: Long = 12345678900
println("Long variable : $longVar")

// Float : single precision 32 bit float point
var floatVar: Float = 123.4F // F is mandatory at end else compile time error
println("Float variable : $floatVar")

// Double : precision 64 bit floating value
var doubleVar: Double = 1234.56
println("Double variable : $doubleVar")


// Characters
// Char
var charVar: Char = 'A'
println("Char variable : $charVar")

// Boolean - this takes only two values - true/false
var booleanVar: Boolean = true
println("Boolean variable : $booleanVar")

var booleanVarFalse: Boolean = false
println("Boolean variable false : $booleanVarFalse")

// Arrays
// implicit type declaration
var array1  = listOf(1,2,3,4,5)

// explcit type declaration
var array2  = listOf<Long>(1,2,3,4,5)

Output:
Byte variable : 100
Short variable : -1000
Int variable : 12345
Long variable : 12345678900
Float variable : 123.4
Double variable : 1234.56
Char variable : A
Boolean variable : true
Boolean variable false : false

9. Conclusion


In this tutorial, we have seen how declare the variables example programs and other interesting stuff for kotlin programmers.


Kotlin Ternary Conditional Operator Examples

1. Overview


In this article, We will learn Ternary Operator in Kotlin and this is part of conditional statements. But, confirming now there is no ternary conditional operator in kotlin language. Let us see how we can simulate or mimic the same using other condition statements available. By the end of this article, you will understand why no ternary conditional operator introduced in kotlin.

If you are new to kotlin language, see the simple hello world-first program in kotlin.

This can be achieved using if-else and when statements.

Kotlin Ternary Conditional Operator


الثلاثاء، 5 يناير 2021

Kotlin - Convert List to Map Examples

1. Overview

In this tutorial, We'll learn how to convert the List to Map in Kotlin programming. Let us explore the different ways to do this conversion.

Kotlin provides a set of methods for the functionality.

  • associate()
  • associateBy()
  • map() and toMap()
  • Running for loop and set to map
First created a Website class with site name and its rank value. Next, Created and added 4 objects to list.

Converting the List to Map is shown in the below sections with example programs.

Kotlin - Convert List to Map Examples



2. Kotlin List to Map with associate() method


Use associate() method to convert the List of object to Map with the needed type for key, value pairs.

Pass the Pair() object with the key, value pair object and internally it iterates over the loop.

package com.javaprogramto.kotlin.collections.list.map

data class Website(var site: String, var rank: Long);

fun main(args: Array<String>) {

    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    println("List values : $websiteranks")

    val finalMap : Map<String, Long> = websiteranks.associate { Pair(it.site, it.rank) };

    println("Final map from list using associate : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associate { Pair(it.site, it) };
    println("Map value as custom type using associate : $mapValueCustomType")

}

Output:
List values : [Website(site=google.com, rank=1), Website(site=youtube.com, rank=2), Website(site=amazon.com, rank=3), Website(site=yahoo.com, rank=4)]
Final map from list using associate : {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associate : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}

3. Kotlin List to Map with associateBy() method


Next, use the associateBy() method to convert list to map in another way.

package com.javaprogramto.kotlin.collections.list.map

fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<String, Long> = websiteranks.associateBy({it.site}, {it.rank});

    println("Final map from list using associateBy: $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associateBy({it.site}, {it})
    println("Map value as custom type using associateBy : $mapValueCustomType")

}

Output:

Final map from list using associateBy: {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associateBy : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}


4. Kotlin List to Map with map() and toMap() methods


Next, use map() and toMap() methods on the list object.

map() method returns ArrayList.
toMap() method returns Map object.

package com.javaprogramto.kotlin.collections.list.map

// kotlin program to convert list to map using map() and toMap() methods.
fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<Long, String> = websiteranks.map { it.rank to it.site }.toMap()

    println("Final map from list using map() and toMap() methods : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.map{it.site to it}.toMap();
    println("Map value as custom type using map() and toMap() methods : $mapValueCustomType")

}

Output:
Final map from list using map() and toMap() methods : {1=google.com, 2=youtube.com, 3=amazon.com, 4=yahoo.com}
Map value as custom type using map() and toMap() methods : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}


5. Kotlin List to Map Using Loops


Finally, Look at the conversion to Map using for loops with normal iteration. In this way, we get the each value from list and set to a new map.

// kotlin program to convert list to map using for each loop
fun main(args: Array<String>) {
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap: MutableMap<String, Long> = HashMap();

    for (website in websiteranks) {
        finalMap[website.site] = website.rank;
    }

    println("Map from list using custom iterating the list with for loop : $finalMap")

}

Output:
Map from list using custom iterating the list with for loop : {google.com=1, amazon.com=3, yahoo.com=4, youtube.com=2}

6. Conclusion


In this article, we have seen the different ways to do conversion from List to Map.

Among all methods, associate() method is the right choice and mostly used in the real time applications.
Next, use toMap() method if you are iterating the list and doing some other operations. 

But, toMap() method is more readable. 


Java Fibonacci Series Recursive Optimized using Dynamic Programming

1. Overview

In this article, we will learn how to print the fibonacci series and find the nth fibonacci number using recursive approach.

Printing the Fibonacci series be done using the iterative approach using while and for loop.

In the following sections we will try to run the program for below scenarios.

  • Print the fibonacci series for the given number
  • Find the nth fibonacci number

In each approach, we will try to see the amount of time taken to process the logic and how it can be optimized using dynamic programming memoization technique.

Java Fibonacci Series Recursive Optimized using Dynamic Programming


2. Print the Fibonacci series using recursive way

Below program to display the first n Fibonacci number using recursive approach. For each input, we are going to print the time taken and compare for different inputs.


package com.javaprogramto.programs.numbers.fibonacii;

import java.time.Instant;

public class PrintFibonaciiSeriesRecursive {

	public static void main(String[] args) {

		long fibResult = 0;

		System.out.println("First 30 fibonacii series numbers : ");
		long startTime = Instant.now().toEpochMilli();

		for (int i = 1; i < 30; i++) {
			fibResult = fibonacii(i);
			System.out.print(fibResult + " ");
		}
		long endTime = Instant.now().toEpochMilli();

		System.out.println("\nExecution time " + (endTime - startTime) + " ms");

		System.out.println("\nFirst 50 fibonacii series numbers : ");
		startTime = Instant.now().toEpochMilli();

		for (int i = 1; i < 50; i++) {
			fibResult = fibonacii(i);
			System.out.print(fibResult + " ");
		}
		endTime = Instant.now().toEpochMilli();

		System.out.println("\nExecution time " + (endTime - startTime) + " ms");

	}

	// fibonacii recursive
	private static long fibonacii(long n) {

		if (n <= 2) {
			return 1;
		}
		long fibNumber = fibonacii(n - 1) + fibonacii(n - 2);

		return fibNumber;
	}
}


Output:

First 30 fibonacii series numbers : 
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 
Execution time 6 ms

First 50 fibonacii series numbers : 
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 
Execution time 53397 ms

From the output, we can understand that to print first 30 fibonacci numbers it took just 6 milli seconds but to print the first 50, it took around 54 seconds.


Time complexity: O(2^n)

Space complexity: 

3. Print the Fibonacci series using recursive way with Dynamic Programming

In the above program, we have to reduce the execution time from O(2^n).

If you observe the above logic runs multiple duplicates inputs.

Look at the below recursive internal calls for input n which is used to find the 5th Fibonacci number and highlighted the input values that are processed by our function multiple times.

2nd Fibonacci number is calculated 3 times.

Print the Fibonacci series using recursive way with Dynamic Programming-1


3rd fibonacci number is calculated twice.


Print the Fibonacci series using recursive way with Dynamic Programming-2

If the input value is 50 there are many inputs are reprocessed for the same inputs which kills the system.

From these analysis, if we can store these values in the memory we can avoid reprocessing them and retrieve the values from memory. This process is called as memoization.

Memoization make sure alway it runs for the different inputs and not for the same inputs again. Instead, gets the values from previous results from memory.

We can use HashMap for storing the intermediate key value pairs.

The below is the optimized program that takes less time for bigger inputs.


package com.javaprogramto.programs.numbers.fibonacii;

import java.time.Instant;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;

public class PrintFibonaciiSeriesRecursiveOptimized {

	public static void main(String[] args) {

		long fibResult = 0;
		Map<Integer, Long> memory = new HashedMap<>();

		System.out.println("First 30 fibonacii series numbers : ");
		long startTime = Instant.now().toEpochMilli();

		for (int i = 1; i < 30; i++) {
			fibResult = fibonacii(i, memory);
			memory.clear();
			System.out.print(fibResult + " ");
		}
		long endTime = Instant.now().toEpochMilli();

		System.out.println("\nExecution time " + (endTime - startTime) + " ms");

		memory.clear();
		
		System.out.println("\nFirst 50 fibonacii series numbers : ");
		startTime = Instant.now().toEpochMilli();

		for (int i = 1; i < 50; i++) {
			fibResult = fibonacii(i, memory);
			memory.clear();
			System.out.print(fibResult + " ");
		}
		endTime = Instant.now().toEpochMilli();

		System.out.println("\nExecution time " + (endTime - startTime) + " ms");

	}

	// fibonacii recursive
		private static long fibonacii(int n, Map<Integer, Long> memory) {
			
			if(memory.get(n) != null) {
				return memory.get(n);
			}

			if (n <= 2) {
				return 1;
			}

			long fib = fibonacii(n - 1, memory) + fibonacii(n - 2, memory);
			
			memory.put(n, fib);
			
			return fib;
		}
}

Output:

First 30 fibonacii series numbers : 
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 
Execution time 2 ms

First 50 fibonacii series numbers : 
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 
Execution time 3 ms

From the above output, you can see the for bigger inputs just took 3ms which is fabulous. We brought down to 3 milli seconds from 54 seconds. 

This is the power of the dynamic programming technique.


4. Find the nth Fibonacci number using recursive way

The below example program to get the nth fibonacci number from the series recursively.


package com.javaprogramto.programs.numbers.fibonacii;

import java.time.Instant;

public class FindFibonaciiNumberRecursive {

	public static void main(String[] args) {
		long startTime = Instant.now().toEpochMilli();
		long finResult = fibonacii(30);
		long endTime = Instant.now().toEpochMilli();

		System.out.println("30th fiboncaii number - " + finResult + " execution time " + (endTime - startTime) + " ms");

		startTime = Instant.now().toEpochMilli();
		finResult = fibonacii(50);
		endTime = Instant.now().toEpochMilli();

		System.out.println("50th fiboncaii number - " + finResult + " execution time " + (endTime - startTime) + " ms");
	}

	
	// fibonacii recursive
	private static long fibonacii(long n) {

		if (n <= 2) {
			return 1;
		}

		return fibonacii(n - 1) + fibonacii(n - 2);
	}
}

Output:

30th fiboncaii number - 832040 execution time 5 ms
50th fiboncaii number - 12586269025 execution time 34413 ms


Take taken for 30th fibonacci number is 5 ms

50th Fibonacci number is 34 seconds.

Time Complexity - O(2^n)

Space Complexity - O(2^n)


5. Find the nth Fibonacci number using recursive way Using Dynamic Programming

Next, let us simplify the above code using memoization technique using hashmap


package com.javaprogramto.programs.numbers.fibonacii;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class FindFibonaciiNumberRecursiveOptimized {

	public static void main(String[] args) {
		
		Map<Integer, Long> memory = new HashMap<>();
		
		long startTime = Instant.now().toEpochMilli();
		long finResult = fibonacii(30, memory);
		long endTime = Instant.now().toEpochMilli();

		System.out.println("30th fiboncaii number - " + finResult + " execution time " + (endTime - startTime) + " ms");

		// clearing the memoization map
		memory.clear();
		
		startTime = Instant.now().toEpochMilli();
		finResult = fibonacii(50, memory);
		endTime = Instant.now().toEpochMilli();

		System.out.println("50th fiboncaii number - " + finResult + " execution time " + (endTime - startTime) + " ms");
	}

	
	// fibonacii recursive
	private static long fibonacii(int n, Map<Integer, Long> memory) {
		
		if(memory.get(n) != null) {
			return memory.get(n);
		}

		if (n <= 2) {
			return 1;
		}

		long fib = fibonacii(n - 1, memory) + fibonacii(n - 2, memory);
		
		memory.put(n, fib);
		
		return fib;
	}
}


Output:

30th fiboncaii number - 832040 execution time 0 ms
50th fiboncaii number - 12586269025 execution time 0 ms


In this approach, if we want to calculate the 5th Fibonacci number from series, it calculates the only the lest side values from the recursive tree.

Find the nth Fibonacci number using recursive way Using Dynamic Programming

So, it reduces the logic execution from 2^n to n times.

Time Complexity : O(2^n)

Space Complexity : O(n) because it still holds the n level runtime stack.


6. Conclusion

In this article, we have seen how to implement the fibonacci series and find nth fibonacci number using recursive approach and optimized way using dynamic programming technique.

GitHub

Java Programs

HashMap Examples

الجمعة، 1 يناير 2021

How To Get Current Date, Time and Timestamp In Java 8?

1. Overview

In this article, we will learn how to get current date, time and timestamp in java 8. 

Let us explore the java 8 new classes LocalDateTime, LocalDate, LocalTime and Instant to work with date and time values of Date Time api.

How To Get Current Date, Time and Timestamp In Java 8?



2. How to get current date in java 8


Use java.time.LocalDate class to get the current date in format of "yyyy-MM-dd" using now() method.

And also we can get the current date from any timezone using now(ZoneId.of()).

Finally, let us convert LocalDateTime to LocalDate object using toLocalDate() method.

In the below example. we have shown the different ways to retrieve the date object in java 8.
package com.javaprogramto.java8.dates.currentdate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class CurrentDate {

	public static void main(String[] args) {
		
		// getting the current date from LocalDate.now() method
		LocalDate currentDate = LocalDate.now();
		
		System.out.println("Current Date from LocalDate : "+currentDate);
		
		// Getting the current daet in Gmt +5
		LocalDate gmtPlus5 = LocalDate.now(ZoneId.of("GMT+05"));
		
		System.out.println("Current time in GMT +05:00 : "+gmtPlus5);
		
		// Gettting the date from LocalDateTime object.
		LocalDateTime localDateTime = LocalDateTime.now();
		LocalDate fromLocalDateTime = localDateTime.toLocalDate();
		System.out.println("From LocalDateTime : "+fromLocalDateTime);
	}
}

Output:
Current Date from LocalDate : 2021-01-01
Current time in GMT +05:00 : 2021-01-01
From LocalDateTime : 2021-01-01

In the output, we could see the same date because timezone date is falling the current date even adding +5 hours. If we are at the end of the day then you can see the different date.

3. How to get current time in java 8


To retrieve the only time part, we can use java.time.LocalTime class. LocalTime.now() method gets the time parts from system date in format hh:mm:ss.sssss.

Use now(ZoneId.of()) method returns the time in the given timezone.

And also we can get the time from LocalDateTime object using toLocalTime() method.

package com.javaprogramto.java8.dates.currentdate;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;

public class CurrentTime {

	public static void main(String[] args) {
		
		// getting the current date from LocalTime.now() method
		LocalTime currentDate = LocalTime.now();
		
		System.out.println("Current time from LocalTime in IST (+05:30): "+currentDate);
		
		// Getting the current daet in Gmt +5
		LocalTime gmtPlus5 = LocalTime.now(ZoneId.of("GMT+06:30"));
		
		System.out.println("Current time in GMT +05:00 : "+gmtPlus5);
		
		// Gettting the date from LocalTimeTime object.
		LocalDateTime LocalTimeTime = LocalDateTime.now();
		LocalTime fromLocalTimeTime = LocalTimeTime.toLocalTime();
		System.out.println("From LocalDateTime : "+fromLocalTimeTime);
	}
}

Output:
Current time from LocalTime in IST (+05:30): 17:52:08.567623
Current time in GMT +05:00 : 18:52:08.568073
From LocalDateTime : 17:52:08.568161

4. How to get current timestamp in java 8


By using java.time.Instant class to get the current timestamp in milli seconds and seconds.

Use Insant.toEpochMilli() and Instant.getEpochSecond() methods to get the current time in milliseconds and seconds respectively.

package com.javaprogramto.java8.dates.currentdate;

import java.time.Instant;

public class CurrentTimeStamp {

	public static void main(String[] args) {
		
		// getting the current timestamp from Instant.now() method
		Instant currentInstant = Instant.now();
		
		// getting the current time in milliseoconds from Instant
		long timeInMillis = currentInstant.toEpochMilli();
		
		System.out.println("Current timestamp in milli seconds "+timeInMillis);

		// Getting the current instant in seconds
		long timeInSeconds = currentInstant.getEpochSecond();
		
		System.out.println("Current timestamp in seconds : "+timeInSeconds);
	}
}

Output:
Current timestamp in milli seconds 1609504761862
Current timestamp in seconds : 1609504761

5. Conclusion


In this article, we've seen how to get the current date, time and timestamp objects using java 8 api.


Java 8 LocalDate Class With Examples

1. Overview

In this tutorial, you'll learn how to use LocalDate class in java 8 Date Time API and its methods with example programs.

In java 8, LocalDate class is an immutable class to represent the date with the default format of "yyyy-MM-dd".

And LocalDate does not represent the time part of date or timezone.

This is mainly used to store the date of birth or date of join because this object works with only with year, month and day but not with the hours, minutes and seconds.

Java 8 LocalDate Class With Examples


2. Java 8 LocalDate Class

This class is defined as final class in the api and implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable interfaces.

How to get the current date and time in java 8?

LocalDate class has many useful methods which reduces the manual work to write the date utility methods.

below are the few methods which are frequently used by the developers.

LocalDate of(int year, int month, int dayOfMonth): Creates a new LocalDate object with the given date parameters.

LocalDateTime atTime(int hour, int minute): It is used to combine this date with a time to create a LocalDateTime.

int compareTo(ChronoLocalDate other): It is used to compares this date to another date.

boolean equals(Object obj): It is used to check if this date is equal to another date.

String format(DateTimeFormatter formatter): It is used to format this date using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date as an int.

boolean isLeapYear(): It is used to check if the year is a leap year, according to the ISO proleptic calendar system rules.

LocalDate minusDays(long daysToSubtract): It is used to return a copy of this LocalDate with the specified number of days subtracted.

LocalDate minusMonths(long monthsToSubtract): It is used to return a copy of this LocalDate with the specified number of months subtracted.

static LocalDate now(): It is used to obtain the current date from the system clock in the default time-zone.

LocalDate plusDays(long daysToAdd): It is used to return a copy of this LocalDate with the specified number of days added.

LocalDate plusMonths(long monthsToAdd): It is used to return a copy of this LocalDate with the specified number of months added.


3. LocalDate Examples

Next, let us see the how to use these methods to work with dates such as adding days, comparing the dates, checking the leap year. etc.

All methods of LocalDate class recreates the new object the modified data.

To see the contents of LocalDate object, write the object onto the log or console. Because, toString() method is overridden in this class and it returns the date in the redable format "yyyy-MM-dd"

3.1 Example 1: Create Objects for LocalDate

LocalDate has 2 methods to create the date objects and those are now() and of() methods.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class LocalDateCreation {

	public static void main(String[] args) {

		// Dates creation with now() and of() methods.
		LocalDate currentDate = LocalDate.now();
		LocalDate futureDate = LocalDate.of(2025, 10, 10);

		// printing the dates.
		System.out.println("Current date : " + currentDate);
		System.out.println("Future date : " + futureDate);

	}

} 

Output:

Current date : 2020-11-23
Future date : 2025-10-10
 

3.2 Example 2:  Adding days and getting next, previous days

Use plusDays() and minusDays() methods to get the next or previous days.

And you go add or go back to a particular day using these two methods.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class AddingDaysExample {

	public static void main(String[] args) {
		// creating current date time
		LocalDate currentDate = LocalDate.now();
		
		// Getting the next date
		LocalDate nextDay = currentDate.plusDays(1);
		
		// Getting the previous date
		LocalDate previousDay = currentDate.minusDays(1);
		
		System.out.println("Current date : "+currentDate);
		System.out.println("Next date : "+nextDay);
		System.out.println("Previous date : "+previousDay);
	}
}
 

Output:

Current date : 2020-11-23
Next date : 2020-11-24
Previous date : 2020-11-22
 

3.3 Example 3:  Checking Leap Year

Call isLeapYear() method from LocalDate class. This method returns boolean as true if the year is leap year else false.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

public class LeapYearExample {
	public static void main(String[] args) {
		//	Example 1 - leap year checking
		LocalDate date1 = LocalDate.now();
		boolean isLeapYear = date1.isLeapYear();
		System.out.println(date1 + " is leap year ? " + isLeapYear);

		//	Example 2
		LocalDate date2 = LocalDate.of(2000, 01, 01);
		isLeapYear = date2.isLeapYear();
		System.out.println(date2 + " is leap year ? " + isLeapYear);

		//	Example 3
		LocalDate date3 = LocalDate.of(2006, 01, 01);
		isLeapYear = date3.isLeapYear();
		System.out.println(date3 + " is leap year ? " + isLeapYear);
	}
}

 

Output:

2020-11-23 is leap year ? true
2000-01-01 is leap year ? true
2006-01-01 is leap year ? false

 

3.4 Example 4: Convert LocalDate to String

Use format() method to convert LocalDate to String in java 8.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateToStringExample {

	public static void main(String[] args) {

		// Converting LocalDate to String
		// Example 1
		LocalDate date1 = LocalDate.now();
		String date1Str = date1.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date1 in string :  " + date1Str);

		// Example 2
		LocalDate date2 = LocalDate.of(2000, 01, 01);
		String date2Str = date2.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date2 in string :  " + date2Str);

		// Example 3
		LocalDate date3 = LocalDate.of(2006, 01, 01);
		String date3Str = date3.format(DateTimeFormatter.ISO_DATE);
		System.out.println("Date3 in string :  " + date3Str);
	}
}
 

Output:

Date1 in string :  2020-11-23
Date2 in string :  2000-01-01
Date3 in string :  2006-01-01
 

3.5 Example 5: Convert String To LocalDate

Use parse() method to convert String to LocalDate.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

// String to LocalDate in java 8
public class StringToLocalDateExample {

	public static void main(String[] args) {

		// Example 1
		String dateInStr = "2021-01-01";
		LocalDate date1 = LocalDate.parse(dateInStr);
		System.out.println("String to LocalDate : " + date1);

		// Example 2
		String dateInStr2 = "2025-11-30";
		LocalDate date2 = LocalDate.parse(dateInStr2);
		System.out.println("String to LocalDate : " + date2);

	}

}
 

3.6 Example 6: Convert LocalDate to LocalDateTime

Use atTime() method to convert LocalDate to LocalDateTime.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class LocalDateAtTimeExample {

	public static void main(String[] args) {
		// localdate 
		LocalDate localDate = LocalDate.now();
		
		int hour = 10;
		int minute = 20;
		int second = 30;
		
		// setting time details and converting LocalDate to LocalDateTime.
		LocalDateTime dateAndTime = localDate.atTime(hour, minute, second);
		
		System.out.println("LocalDate : "+localDate);
		System.out.println("LocalDateTime : "+dateAndTime);

	}

}
 

Output:

LocalDate : 2020-11-23
LocalDateTime : 2020-11-23T10:20:30
 


4. Conclusion

In this article, you have seen What is LocalDate class in java 8 and how to LocalDate class methods with examples.

GitHub

LocalDateCreation

AddingDaysExample

LeapYearExample

LocalDateAtTimeExample

LocalDateToStringExample

StringToLocalDateExample

Read Next:

How to convert Calendar to LocalDate ?

How to compare two dates in java 8?

How to add days to current time in java 8?

LocalDate