Tuesday, December 22, 2020

How To Convert Epoch time MilliSeconds to LocalDate and LocalDateTime in Java 8?

1. Overview

In this article, We'll learn how to convert the time from epoch milliseconds to LocalDate or LocalDateTime in java 8.

But, Converting epoch time to LocalDate or LocalDateTime can not be done directly so we need to convert first to ZonedDateTime and then next to needed type such as LocalDate or LocalDateTime.

Use Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()) method and next use either toLocalDate() or toLocalDateTime() methods.

How To Convert Epoch time MilliSeconds to LocalDate and LocalDateTime in Java 8?


2. Java 8 - Convert Epoch to LocalDate


Below is the sample program to get the LocalDate from epoch time.

In this program, first we have shown the step by step to get the required objects to get the LocalDate and finally shown the simplified the code in single line to get the same.

package com.javaprogramto.java8.dates.milliseconds;

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

/**
 * 
 * java Example to convert millisconds to LocalDate
 * 
 * @author JavaProgramTo.com
 *
 */
public class EpochMillisToLocalDate {

	public static void main(String[] args) {

		// current time in epoch format
		long epochMilliSeconds = 1608647457000l;
		
		// epoch time to Instant
		Instant instant = Instant.ofEpochMilli(epochMilliSeconds);
		
		// Instant to ZonedDateTime
		ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
		
		// ZonedDateTime to LocalDate
		LocalDate localDate1 = zonedDateTime.toLocalDate();
		
		System.out.println("LocalDate 1 : "+localDate1);
		
		// simplified code
		LocalDate localDate2 = Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()).toLocalDate();

		System.out.println("LocalDate 2 : "+localDate2);
	}
}

Output:
LocalDate 1 : 2020-12-22
LocalDate 2 : 2020-12-22


3. Java 8 - Convert Epoch to LocalDateTime


The below example is to retrieve the LocalDateTime object from milliseconds.
package com.javaprogramto.java8.dates.milliseconds;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * 
 * java Example to convert millisconds to LocalDateTime
 * 
 * @author JavaProgramTo.com
 *
 */
public class EpochMillisToLocalDateTime {

	public static void main(String[] args) {

		// current time in epoch format
		long epochMilliSeconds = 1608647457000l;
		
		// epoch time to Instant
		Instant instant = Instant.ofEpochMilli(epochMilliSeconds);
		
		// Instant to ZonedDateTime
		ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
		
		// ZonedDateTime to LocalDate
		LocalDateTime localDateTime1 = zonedDateTime.toLocalDateTime();
		
		System.out.println("LocalDateTime 1 : "+localDateTime1);
		
		// simplified code
		LocalDateTime localDateTime2 = Instant.ofEpochMilli(epochMilliSeconds).atZone(ZoneId.systemDefault()).toLocalDateTime();

		System.out.println("LocalDateTime 2 : "+localDateTime2);
	}
}

Output:
LocalDateTime 1 : 2020-12-22T20:00:57
LocalDateTime 2 : 2020-12-22T20:00:57

4. Conclusion


In this article, we've seen how to do conversion epoch millis to LocalDate or LocalDateTime in java 8.




Monday, December 21, 2020

Java String subSequence() Examples - Print subSequence in String

1. Overview


In this article, You'll learn how to get the subsequence from a String. This looks similar to the java string substring() method but the substring method returns a new String but subSequence method returns CharSequence rather than String.

Java String subSequence() Examples - Print subSequence in String

Java.lang.System.currentTimeMillis() Method Example

1. Overview

In this tutorial, We'll learn how to get the current time value in milliseconds in java

Java api provides a utility class System in java.lang package and System class has static method which can be directly invoked as System.currentTimeMillis().

Java.lang.System.currentTimeMillis() Method Example


2. Syntax

public static long currentTimeMillis()


From syntax, we can see that it returns a long value in milli seconds time unit.

The returned value is dependent on the underlying operating system. For example, some of the operating systems generates the time in tens of milliseconds.

This method returns the value that is difference between the current system time and coordinated UTC time 1970.


3. System.currentTimeMillis() Examples


The below example is on how to use System.currentTimeMillis() method.

package com.javaprogramto.java8.dates;

import java.sql.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import org.joda.time.DateTime;

/**
 * Example to get the current time in milli seconds.
 * 
 * @author JavaProgramTo.com
 *
 */
public class CurrentTimeSystemCurrentTimeMillis {

	public static void main(String[] args) {

		// calling currentTimeMillis() method
		long currentTimeMillis = System.currentTimeMillis();
		System.out.println("Current time in millies - "+currentTimeMillis);
		
		// using Date(long) constructor
		Date date = new Date(currentTimeMillis);
		System.out.println("Date : "+date);
		
		// java 8
		LocalDateTime localDateTime = Instant.ofEpochMilli(currentTimeMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
		System.out.println("Java 8 localdate time : "+localDateTime);
	}
}

Output:

Current time in millies - 1608565975991
Date : 2020-12-21
Java 8 localdate time : 2020-12-21T21:22:55.991


In the above program, First we have retrieved the current date and time in milli seconds as long value and next converted the long value into Date value.

And also converted the long value into LocalDateTime object in java 8.


4. Conclusion

In this article, We've seen how to get the current date time in milli seconds in java.

GitHub

Java 8 Date Time Examples

Tuesday, December 15, 2020

How To Get Current Date and Time in Java 8 and Older?

1. Overview

In this tutorial, We'll learn how to get the current date and time in java and new date time api in java 8.

There are different classes in java to get the current date and time and let us explore the example programs.

java.util.Date
Java 8 - java.time.Clock
java.util.Calendar
java.sql.Date
java.text.SimpleDateFormat
Java 8 - java.time.LocalDate
Java 8 - java.time.LocalTime
Java 8 - java.time.LocalDateTime
Java 8 - java.time.ZonedDateTime
Java 8 - java.time.format.DateTimeFormatter

How To Get Current Date and Time in Java 8 and Older?


2. Using java.util.Date


Use the util Date class constructor to get the current date and time values.

package com.javaprogramto.java8.dates.getdatetime;

import java.util.Date;

public class DateExample {

	public static void main(String[] args) {

		// using new Date()
		Date currentDateTime = new Date();
		System.out.println("Current date time using Date() : " + currentDateTime);

		// using System.currentTimeMillis()
		long milliSeconds = System.currentTimeMillis();
		currentDateTime = new Date(milliSeconds);
		System.out.println("Current date time using System.currentTimeMillis() : " + currentDateTime);
	}
}

Output:

Current date time using Date() : Tue Dec 15 20:47:44 IST 2020
Current date time using System.currentTimeMillis() : Tue Dec 15 20:47:44 IST 2020

3. Using java.util.Calendar


Use Calendar.getTime() method to get the Date instance.

package com.javaprogramto.java8.dates.getdatetime;

import java.util.Calendar;
import java.util.Date;

public class CalendarExample {

	public static void main(String[] args) {
		
		// Getting the calendar object
		Calendar cal = Calendar.getInstance();

		// Getting the util Date.
		Date currentDateTime = cal.getTime();
		System.out.println("Current Date Time : "+currentDateTime);
	}
}

Output:

Current Date Time : Tue Dec 15 20:51:02 IST 2020

4. Using java 8 - java.time.Clock


Use java 8 new method Instant() method from Clock class.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.Clock;
import java.time.Instant;

public class ClockExample {

	public static void main(String[] args) {
		Clock clockInUTC = Clock.systemUTC();
		Instant instnat = clockInUTC.instant();
		
		System.out.println("Java 8 - Current date time : "+instnat);
	}
}

Output:


5. Using java.sql.Date


This sql Date class returns only the Date part without time units. Pass the time in milliseconds to the sql Date() constructor and returns the date.

package com.javaprogramto.java8.dates.getdatetime;

import java.sql.Date;

public class SqlDateExample {

	public static void main(String[] args) {
		
		long timeInMillis = System.currentTimeMillis();
		
		Date sqlDate = new Date(timeInMillis);
		
		System.out.println("Current date from sql date : "+sqlDate);
	}
}

Output:
Current date from sql date : 2020-12-15

6. Using java.text.SimpleDateFormat


Use SimpleDateFormat class to get the date and time in our custom desired format.

Next, call format() method with the util Date and returns date in string format.

package com.javaprogramto.java8.dates.getdatetime;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

	public static void main(String[] args) {

		// current date custom format
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		
		// current date and time
		Date currentDate = new Date();
		
		// Util Date to String using format()
		String strDate = dateFormatter.format(currentDate);

		System.out.println("Current Date using SimpleDateFormat : "+strDate);
	}
}

Output:

Current Date using SimpleDateFormat : 2020-12-15 09:20

7. Using Java 8 - java.time.LocalDate


Use LocalDate.now() method to get the current date. This method does not return the time formats and stores the only date values.

Note: If you want to get only date part in java 8 then use LocalDate class.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDate;

public class LocalDateExample {
	
	public static void main(String[] args) {
		
		// using LocalDate class
		LocalDate localDateCurrentDate = LocalDate.now();
		
		// print the current date
		System.out.println("LocalDate current date : "+localDateCurrentDate);
	}
}

Output:

LocalDate current date : 2020-12-15

8. Using Java 8 - java.time.LocalTime


In java 8, LocalTime class works opposite to the LocalDate class and LocalTime.now() method gives only time part with milli seconds by default.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalTime;

public class LocalTimeExample {

	public static void main(String[] args) {
		
		// Using LocalTime class now() method
		LocalTime localTimeCurrentTime = LocalTime.now();
		
		// using 
		System.out.println("LocalTime : "+localTimeCurrentTime);
	}
}
Output:
LocalTime : 21:28:59.495299

9. Using Java 8 - java.time.LocalDateTime


Another class from java 8 LocalDateTime class which gives both date and time part. Use now() method to get the current date and time.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDateTime;

public class LocalDateTimeExample {

	public static void main(String[] args) {
		
		// using LocalDateTime class now() method
		LocalDateTime now = LocalDateTime.now();
		
		// printing
		System.out.println("Current date time from LocalDateTime : "+now);
	}
}

Output:
Current date time from LocalDateTime : 2020-12-15T21:33:16.944571

10. Using Java 8 - java.time.ZonedDateTime


Next java 8 class is ZonedDateTime and this works with timezone part along with the date time.

Use now() method to get the current date time from the current timezone.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.ZonedDateTime;

public class ZonedDateTimeExample {

	public static void main(String[] args) {

		// Using ZonedDateTime class now() method
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		
		// print current date time from ZonedDateTime class.
		System.out.println("ZonedDateTime : "+zonedDateTime);
	}
}

Output:
ZonedDateTime : 2020-12-15T21:36:12.881014+05:30[Asia/Kolkata]

11. Using Java 8 - java.time.format.DateTimeFormatter


Use DateTimeFormatter class to get the date in custom format in java 8 api.

Pass the date pattern to DateTimeFormatter.ofPattern() method and format() method to get the LocalDateTime or ZonedDateTime in string format.

package com.javaprogramto.java8.dates.getdatetime;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExamples {

	public static void main(String[] args) {
		DateTimeFormatter formatterInJava8 = DateTimeFormatter.ofPattern("yyyy/MMM/dd HH:mm:ss");
		
		LocalDateTime LocalDateTimeCurrentTime = LocalDateTime.now();
		String date1 = formatterInJava8.format(LocalDateTimeCurrentTime);

		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		String date2 = formatterInJava8.format(zonedDateTime);
		
		System.out.println("Date in custom format : ");
		System.out.println("Current date time from LocalDateTime : "+date1);
		System.out.println("Current date time from ZonedDateTime : "+date2);
	}
}

Output:
Date in custom format : 
Current date time from LocalDateTime : 2020/Dec/15 21:41:17
Current date time from ZonedDateTime : 2020/Dec/15 21:41:17

12. Conclusion


In this article, we've seen various ways to get the date and time in java older versions and new java 8 api with examples.



Saturday, December 12, 2020

Java - Get Time In MilliSeconds

1. Overview

In this tutorial, We'll learn how to get the time in milliseconds in java. Time in milliseconds is the right way and format in storing into the database for date time columns. Because this is stored as Number type and which reduces the space than DateTime type in SQL.

Let us come to our topic today is getting the time milliseconds can be retrieved from Date, Calendar and java 8 api classes such Instant, ZonedDateTime classes.

Java - Get Time In MilliSeconds


2. Using java.util.Date


First, we'll try with the simple way to get the time in milliseconds format is from Date class. Date class has a method getTime() which returns the milliseconds in long value for the given time or current time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Date;

/**
 * Example to get time in milli seconds in java using util Date api
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsFromDate {

	public static void main(String[] args) {
		
		// Getting the current date from Date class.
		Date currentDate = new Date();
		
		// Getting the time in milliseconds.
		long milliSeconds = currentDate.getTime();
		
		// printing the values
		System.out.println("Current date : "+currentDate);
		System.out.println("Current date time in milliseconds : "+milliSeconds);
		
		// Creating the future date
		Date futureDate = new Date(2025, 01, 01, 02, 30, 50);
		
		// Getting the future date
		milliSeconds = futureDate.getTime();
		
		// printing the future date time values
		System.out.println("Future date : "+futureDate);
		System.out.println("Future date time in milliseconds : "+milliSeconds);
	}
}

Output:
Current date : Sat Dec 12 21:48:25 IST 2020
Current date time in milliseconds : 1607789905027
Future date : Sun Feb 01 02:30:50 IST 3925
Future date time in milliseconds : 61696501250000

3. Using java.util.Calendar


Next, use the Calendar class to get the time in milli seconds. This class has a method getTimeInMillis() which returns the milliseconds for the time.

package com.javaprogramto.java8.dates.milliseconds;

import java.util.Calendar;
import java.util.Locale;

/**
 * Example to get time in milli seconds in java using Calendar api
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsFromCalendar {

	public static void main(String[] args) {
		
		// Getting the current date from Calendar class.
		Calendar calendar = Calendar.getInstance();
		
		// Getting the time in milliseconds.
		long milliSeconds = calendar.getTimeInMillis();
		
		// printing the values
		System.out.println("Current calender time in milliseconds : "+milliSeconds);
		
		// Creating another calendar object for Canada locale
		Calendar canadaLocale = Calendar.getInstance(Locale.CANADA);
		
		// Getting the future date
		milliSeconds = canadaLocale.getTimeInMillis();
		
		// printing the future date time values
		System.out.println("Future date time in milliseconds : "+milliSeconds);
	}
}

Output:
Current calender time in milliseconds : 1607790439838
Future date time in milliseconds : 1607790439859

4. Using Java 8 API


There are multiple ways to get the date time in milliseconds in java 8 date time api using Instant and ZonedDateTime classes.

Use toEpochMilli() method to get the date time in milli seconds epoch format.

package com.javaprogramto.java8.dates.milliseconds;

import java.time.Instant;
import java.time.ZonedDateTime;

/**
 * Example to get time in milli seconds in java 8 Using ZonedDateTime and Instant.
 * 
 * @author JavaProgramTo.com
 *
 */
public class MilliSecondsInJava8 {

	public static void main(String[] args) {
		
		// Getting milli seconds from ZonedDateTime class.
		
		// Creating zoned date time
		ZonedDateTime dateTime = ZonedDateTime.now();
		
		// getting the instant from zoned date time
		Instant instant = dateTime.toInstant();
		
		// Converting Instant time to epoch format milli seconds
		long timeInMilliSeconds = instant.toEpochMilli();
		
		// print the output
		System.out.println("Milli seconds from ZonedDateTime : "+timeInMilliSeconds);
		
		// Getting the milli seconds from Instant class.
		// Creating Instant object
		Instant instantTime = Instant.now();
		
		// Getting millis epoch value
		timeInMilliSeconds = instantTime.toEpochMilli();
		
		// printing
		System.out.println("Milli seconds from Instant : "+timeInMilliSeconds);
	}
}

Output:
Milli seconds from ZonedDateTime : 1607790957290
Milli seconds from Instant : 1607790957291

5. Conclusion


In this article, we've seen how to get the time in milli seconds in java 8 and older versions with examples.

Date class - use getTime() method
Calender class - use getTimeInMilli()
Java 8 api - use toEpochMilli()


Thursday, December 10, 2020

Java 8 Stream - Convert List to Map

1. Overview

In this tutorial, We'll learn how to convert List to Map using java 8 stream methods.

Use Collectors.toMap() method which collect List into Map instance but we need to provide the values for key and value for output map object.

Once we see the example programs on how to pass key and value to the toMap() method.

Let us explore the different ways to do this.

Java 8 Stream - Convert List to Map


2. Collect List to Map using Collectors.toMap()


First create a list with string values and convert it into Stream using stream() method. Next, call stream.collect(Collectors.toMap()) method to convert list to map.

In the below example, key is the string and value is the length of string.

package com.javaprogramto.java8.arraylist.tomap;

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

public class ListToMapExample {

	public static void main(String[] args) {
		
		// creating a List
		List<String> list = Arrays.asList("one","two","three","four","five");
		
		// List to Stream
		Stream<String> stream = list.stream();
		
		// Stream to map - key is the string and value is its length
		Map<String, Integer> map = stream.collect(Collectors.toMap(String::new, String::length));
		
		// printing input list and map
		System.out.println("List : "+list);
		System.out.println("Map : "+map);
	}
}

Output:
List : [one, two, three, four, five]
Map : {four=4, one=3, two=3, three=5, five=4}


3. Collect List of Custom objects to Map using Collectors.toMap()


Now, let us see how to extract the values for key, value for Map from List.

Create a simple custom class named Book with constructor, setter, getters and toString() method.

package com.javaprogramto.java8.arraylist.tomap;

public class Book {

	private int id;
	private String author;
	private int yearRealeased;

	public Book(int id, String author, int yearRealeased) {
		this.id = id;
		this.author = author;
		this.yearRealeased = yearRealeased;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getYearRealeased() {
		return yearRealeased;
	}

	public void setYearRealeased(int yearRealeased) {
		this.yearRealeased = yearRealeased;
	}

	@Override
	public String toString() {
		return "Book [id=" + id + ", author=" + author + ", yearRealeased=" + yearRealeased + "]";
	}
}

Next, Create List of Books and convert it into Map.

Map1 with key is book id and value is book object
Map2 with key is yearReleased and value is book object
Map3 with key is name and value author name.

Use Function.idendity() method to get the current object from Stream.

package com.javaprogramto.java8.arraylist.tomap;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ListToMapCustomObjects {

	public static void main(String[] args) {
		List<Book> books = Arrays.asList(new Book(100, "book 1", 2017), new Book(101, "book 2", 2018),
				new Book(102, "book 3", 2019), new Book(103, "book 4", 2020));

		// map1 with key = id and value is book object
		Map<Integer, Book> map1 = books.stream().collect(Collectors.toMap(Book::getId, Function.identity()));

		// map2 with key = yearReleased and value is book object
		Map<Integer, Book> map2 = books.stream().collect(Collectors.toMap(Book::getYearRealeased, Function.identity()));

		// map3 with key = author name and value is year released
		Map<String, Integer> map3 = books.stream().collect(Collectors.toMap(Book::getAuthor, Book::getYearRealeased));

		// printing
		System.out.println("List of books --> " + books);
		System.out.println("Map1 --> " + map1);
		System.out.println("Map2 --> " + map2);
		System.out.println("Map3 --> " + map3);
	}
}

Output:
List of books --> [Book [id=100, author=book 1, yearRealeased=2017], Book [id=101, author=book 2, yearRealeased=2018], Book [id=102, author=book 3, yearRealeased=2019], Book [id=103, author=book 4, yearRealeased=2020]]
Map1 --> {100=Book [id=100, author=book 1, yearRealeased=2017], 101=Book [id=101, author=book 2, yearRealeased=2018], 102=Book [id=102, author=book 3, yearRealeased=2019], 103=Book [id=103, author=book 4, yearRealeased=2020]}
Map2 --> {2017=Book [id=100, author=book 1, yearRealeased=2017], 2018=Book [id=101, author=book 2, yearRealeased=2018], 2019=Book [id=102, author=book 3, yearRealeased=2019], 2020=Book [id=103, author=book 4, yearRealeased=2020]}
Map3 --> {book 2=2018, book 1=2017, book 4=2020, book 3=2019}


4. List to Map with Duplicate key


In the above section, we have added the unique values to the key in map. So, we are seeing the output as expected. 

But, What happens if we are adding the key that have duplicate values.

List<String> list = Arrays.asList("one","two","three","four","five", "five");

Now added "five" value twice in the section 2 program. So, run and see the output now.

It has thrown the runtime error " Duplicate key five (attempted merging values 4 and 4)" but this is not expected. We want to merge or replace with the new value for duplicate key.

Error is clearly saying problem with key value "five".

Exception in thread "main" java.lang.IllegalStateException: Duplicate key five (attempted merging values 4 and 4)
	at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
	at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
	at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
	at com.javaprogramto.java8.arraylist.tomap.DuplicatesListToMapExample.main(DuplicatesListToMapExample.java:20)

To solve this duplicate issue, need to use overloaded toMap() with three parameters.

parameter 1 --> for key
parameter 2 --> for value
parameter 3 --> if the key is duplicate what should be the new value

Look at the below modified code in case of duplicates we are adding 1000 to the new value.
Map<String, Integer> map = stream
				.collect(Collectors.toMap(String::new, String::length, (oldValue, newValue) -> newValue + 1000));

Look at the output.

Map : {four=4, one=3, five=1004, three=5, two=3}

We can see in the output that duplicate key five is added with 1000 value.

The same logic, we can apply to the custom objects.

public class DuplicateListToMapCustomObjects {

	public static void main(String[] args) {
		List<Book> books = Arrays.asList(new Book(100, "book 1", 2017), new Book(101, "book 2", 2018),
				new Book(102, "book 3", 2019), new Book(103, "book 4", 2020), new Book(103, "book 3", 2021),
				new Book(102, "book 4", 2019));

		// map1 with key = id and value is book object
		Map<Integer, Book> map1 = books.stream()
				.collect(Collectors.toMap(Book::getId, Function.identity(), (oldValue, newValue) -> newValue));

		// map2 with key = yearReleased and value is book object
		Map<Integer, Book> map2 = books.stream().collect(
				Collectors.toMap(Book::getYearRealeased, Function.identity(), (oldValue, newValue) -> newValue));

		// map3 with key = author name and value is year released
		Map<String, Integer> map3 = books.stream()
				.collect(Collectors.toMap(Book::getAuthor, Book::getYearRealeased, (oldValue, newValue) -> newValue));

		// printing
		System.out.println("List of books --> " + books);
		System.out.println("Map1 --> " + map1);
		System.out.println("Map2 --> " + map2);
		System.out.println("Map3 --> " + map3);
	}
}

Output:
List of books --> [Book [id=100, author=book 1, yearRealeased=2017], Book [id=101, author=book 2, yearRealeased=2018], Book [id=102, author=book 3, yearRealeased=2019], Book [id=103, author=book 4, yearRealeased=2020], Book [id=103, author=book 3, yearRealeased=2021], Book [id=102, author=book 4, yearRealeased=2019]]
Map1 --> {100=Book [id=100, author=book 1, yearRealeased=2017], 101=Book [id=101, author=book 2, yearRealeased=2018], 102=Book [id=102, author=book 4, yearRealeased=2019], 103=Book [id=103, author=book 3, yearRealeased=2021]}
Map2 --> {2017=Book [id=100, author=book 1, yearRealeased=2017], 2018=Book [id=101, author=book 2, yearRealeased=2018], 2019=Book [id=102, author=book 4, yearRealeased=2019], 2020=Book [id=103, author=book 4, yearRealeased=2020], 2021=Book [id=103, author=book 3, yearRealeased=2021]}
Map3 --> {book 2=2018, book 1=2017, book 4=2019, book 3=2021}

5. Conclusion


In this article, We've seen how to collect the List to Map using java 8 Streams method Collectors.toMap() method.

And alos seen how to handle the duplicate keys with toMap() method and its solution.

More over, we can use filter(), map() and sort() method on the stream and finally we can collect the stream into Map.




Creating Infinite Loops In Java

1. Overview

In this tutorial, We'll learn how to create infinite loops in java. Creating infinite loops can be done in different ways using for loop, while loop and do while loops.

Every loop will have the condition and loop will be running untill the condition is satisfied that means condition is returning true value. If the condition is not becoming false then it is called as unlimited or never ending loop.

90% of infinite loops are created are errors by programmers but there are few situation where we use the infinite loops for some logics those should be running for every 15 mins or periodically. These loops will exits only on the termination of application.

Let us explore the different ways.

Creating Infinite Loops In Java


2. Using for loop


First, start with the for loop and use the boolean value true in the condition place inside for loop.

package com.javaprogramto.programs.infinite.loops;

/**
 * Example to create infinite loop with for loop.
 * 
 * @author javaprogramto.com
 *
 */
public class ForLoopInfiniteExample {

	public static void main(String[] args) {

		// for loop condition to true.
		// this loop runs forever.
		for (; true;) {
			// core logic
			System.out.println("Running loop");
		}
	}
}

3. Using while loop


Next, use the while loop with true boolean in condition.

public class WhileLoopInfiniteExample {

	public static void main(String[] args) {

		// while loop condition to true.
		// this loop runs forever.
		while (true) {
			// core logic
			System.out.println("Running while loop");
		}
	}
}

4. Using do while loop


Finally use the do while loop to create infinite loop. But, this is very rarely used in the java and first while block will be executed then condition is checked. 


/**
 * Example to create infinite loop with do-while loop.
 * 
 * @author javaprogramto.com
 *
 */
public class DoWhileLoopInfiniteExample {
	public static void main(String[] args) {

		// do-while loop condition to true.
		do  {
			// core logic
			System.out.println("Running do-while loop");
		} while(true);
	}
}

5. Conclusion


In this article, We've seen how to create infinite loops in java in several ways.



Java 8 - How To Convert Any Stream to List in Java? toList()?

1. Overview

In this tutorial, We'll learn how to convert any type of Stream to List in java 8

Use Collectors.toList() method to convert the lambda Stream Collect to List or ArrayList. When you call toList() method, it creates an ArrayList object and returns to the caller.

But, if you want to get the List as LinkedList then need to use Collectors.toCollection() method.

Let us see the example programs using these two methods for better understanding.

Java 8 - How To Convert Stream to List in Java? Collectors.toList()


2. Java 8 - Convert Stream to List


Below example program to convert a stream to list using Collectors.toList() method with the help of collect() method.

package com.javaprogramto.java8.collectors.streamtolist;

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

/**
 * Example Stream to List
 * 
 * @author javaprogramto.com
 *
 */
public class StreamToListExample {

	public static void main(String[] args) {
		// creating an list
		List<String> names = Arrays.asList("Nick", "Boran", "Tison", "Sunshine");

		// converting list to stream
		Stream<String> stream = names.stream();

		// finally collecting the stream values into a list with any filtering the
		// objects.
		List<String> finalList = stream.collect(Collectors.toList());

		// printing
		System.out.println("List values : " + finalList);
	}
}

Output:

List values : [Nick, Boran, Tison, Sunshine]

3. Java 8 - Numbers Stream to List With filter() - Stream.of()


In this approach, first we will create the Stream of integers as Stream<Integer> using Stream.of() method and pass the numbers to of() method. We can pass any number of int values comma separated to this method. Because this method takes the input var-args.

package com.javaprogramto.java8.collectors.streamtolist;

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

/**
 * Example on numbers Stream to List
 * 
 * @author javaprogramto.com
 *
 */
public class NumbersStreamToListExample {

	public static void main(String[] args) {

		// Creating a stream using of() method.
		Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

		// Filtering the stream values to get only even numbers and next collect into ArrayList.
		List<Integer> finalList = stream.filter(e -> e % 2 == 0).collect(Collectors.toList());

		// printing
		System.out.println("Final ArrayList values : " + finalList);
	}
}

Output:
Final ArrayList values : [2, 4]

In the above program, after adding the first 5 integers to stream and adding filter() to get only the even numbers. Finally, Invoked the collect(Collectors.toList()) method which returns ArrayList instance default and stored the values into the List<Integer> variable.

4. Java 8 Stream to List as LinkedList


In the above sections, we've used Collectors.toList() method to get ArrayList object from stream values. But, if we want to get it as LinkedList then use another Collectors method toCollection() method which takes the LinkedList object as LinkedList::new.

LinkedList::new will create a new LinkedList object using Method Reference concept.

package com.javaprogramto.java8.collectors.streamtolist;

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

/**
 * Example Stream to LinkedList
 * 
 * @author javaprogramto.com
 *
 */
public class StreamToLinkedListExample {

	public static void main(String[] args) {
		// creating an list
		List<String> values = Arrays.asList("1", "2", "3", "4", "5");

		// converting list to stream
		Stream<String> stream = values.stream();

		// Collecting the stream values into a LinkedList using stream collectors.
		LinkedList<String> linkedList = stream.collect(Collectors.toCollection(LinkedList::new));

		// printing
		System.out.println("LinkedList values : " + linkedList);
	}
}

Output:
LinkedList values : [1, 2, 3, 4, 5]

5. Java 8 - Convert Infinite Stream to List


Java 8 api allows to create infinite streams of number using IntStream.iterate() method.

Let us now convert Infinite stream into List with limiting the number values from unlimited stream using limit() method.

Look at the below example.

limit(): taking first 10 values from infinite stream
boxed(): convert primitive to Wrapper integer object.
toList(): collecting stream values into List.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * Example on Infinite Stream to List
 * 
 * @author javaprogramto.com
 *
 */
public class StreamToListExample {

	public static void main(String[] args) {

		// Creating the infinite even numbers stream using iterate() starts from value
		// 10.
		IntStream infiniteStream = IntStream.iterate(10, i -> i + 2);

		// limit() + boxed() + toList() example
		List<Integer> finalList = infiniteStream.limit(10).boxed().collect(Collectors.toList());

		// printing
		System.out.println("List values : " + finalList);
	}
}

Output:
List values : [10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

6. Conclusion


In this article, we've seen how to convert stream to list in java 8. Use Collectors.toList() to get the output in ArrayList object and Collectors.toCollection() method to get the output for other collections as LinkedList.



Wednesday, December 9, 2020

Java 8 Stream foreach Collect - Can not be done?

1. Overview

In this tutorial, We'll see whether can we use the forEach() method in the middle of stream operations such as stream().foreach().collect().

Another one can not we use the stream().forEach() and stream.collect() in one stream?

This is a common doubt for beginners when they start writing the programs in java 8 stream concepts.

First understand that forEach() and collect() methods are the terminal operations. That means theses are designed to produce the output of the stream and next end the stream. And also these two do not produce the stream result. So, we can not call further any stream methods.

We must be clear on Lambda Rules for usage.

But, we are trying to do with the calling forEach() in the middle of stream methods.

Let us see the simple examples.

Java 8 Stream foreach Collect - Can not be done?


2. Java 8 Stream forEach collect Example


Take a list with strings and try to do some filtering and then call forEach(). Finally, call collect method to store the final strings into a ArrayList.

package com.javaprogramto.java8.foreach;

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

public class Java8StreamForEachCollect {

	public static void main(String[] args) {

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

		list.add("hello");
		list.add("world");
		list.add("welcome");
		list.add("to");
		list.add("javaprogramto.com");

		list.stream().filter(value -> value.contains("c")).forEach(value -> value + "-").collect();
	}
}

Now compile this code and see the error.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The method forEach(Consumer<? super String>) in the type Stream<String> is not applicable for the arguments ((<no type> value) -> {})
	Void methods cannot return a value

	at com.javaprogramto.java8.foreach.Java8StreamForEachCollect.main(Java8StreamForEachCollect.java:18)

It is saying forEach() method does not return any value but you are returning string value with "-" and on forEach() method calling collect() method.

Error: Void methods cannot return a value

3. Solve - Stream forEach collect


Actually, If we can see in the forEach method we are trying to do the change the value of string. So, we need to use another method map() rather than forEach() which will do modifying the values and returns a stream of new string values. And further we can collect the result into List and use forEach() method.

And also instead of collecting into list, on map() result we can call forEach() method directly.
package com.javaprogramto.java8.foreach;

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

public class Java8StreamForEachCollect {

	public static void main(String[] args) {

		// creating a list
		List<String> list = new ArrayList<>();

		// adding values to list
		list.add("hello");
		list.add("world");
		list.add("welcome");
		list.add("to");
		list.add("javaprogramto.com");

		// list.stream().filter(value -> value.contains("c")).forEach(value -> value +
		// "-").collect();

		// stream filter() + map() + collect() example
		List<String> newList = list.stream().filter(value -> value.contains("c"))
									.map(value -> value + "-")
									.collect(Collectors.toList());
		
		//printing the list
		System.out.println("Original List : "+list);
		System.out.println("New List Values : ");
		
		// print using forEach on list.
		newList.forEach(value -> System.out.println(value));
		
		// iterating stream using forEach()
		System.out.println("\niterating stream using forEach()");
		list.stream().filter(value -> value.contains("c"))
				.map(value -> value + "-")
				.forEach(str -> System.out.println(str));
	}
}

Output:
Original List : [hello, world, welcome, to, javaprogramto.com]
New List Values : 
welcome-
javaprogramto.com-

iterating stream using forEach()
welcome-
javaprogramto.com-

4. Conclusion


In this article, We've seen how to use the forEach() and collect() methods effectively in java 8 streams.


Monday, December 7, 2020

Java Convert LocalDate to ZonedDateTime

1. Overview

In this tutorial, We'll learn how to convert the LocalDate to ZonedDateTime in java 8.

LocalDate is having only date units without timezone and ZonedDateTime object contains date, time units with timezone information. But, when we want to convert LocalDate to ZonedDateTime, we have to supply the remaining time units and timezone values and add to the LocalDate object.

This is solved using a simple method atStartOfDay() from LocalDate class with ZoneId information as an argument.

Let us explore how to convert String to ZonedDateTime and LocalDate to ZonedDateTime object.

Java Convert LocalDate to ZonedDateTime


2. Java 8 Convert String to ZonedDateTime Object


In the below example, we are taking the string as input date in format "yyyy-MM-dd" and pass to the LocalDate.parse() method and then covert it to the ZonedDateTime object.

package com.javaprogramto.java8.dates.localdate;

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

/**
 * Example to convert String to ZonedDateTime.
 * 
 * @author JavaProgramTo.com
 *
 */
public class StringToZonedDateTimeExample {

	public static void main(String[] args) {

		// date in string format
		String date = "2022-03-02";

		// Converting String to LocalDate.
		LocalDate localDate = LocalDate.parse(date);

		// Creating timezone
		ZoneId zoneid = ZoneId.systemDefault();

		// LocalDate to zoneddatetime
		ZonedDateTime zonedDateTimeFromString = localDate.atStartOfDay(zoneid);

		System.out.println("String date : " + date);
		System.out.println("ZonedDateTime : " + zonedDateTimeFromString);
	}
}
Output:

String date : 2022-03-02
ZonedDateTime : 2022-03-02T00:00+05:30[Asia/Kolkata]

3. Java 8 Convert LocalDate to ZonedDateTime Object


Next, convert the LocalDate object into ZonedDateObject with PST America timezone.

Use atStartOfDay() method with PST timezone is passed using ZoneId.of() method.

package com.javaprogramto.java8.dates.localdate;

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

/**
 * Example to convert LocalDate to ZonedDateTime with PST zone.
 * 
 * @author JavaProgramTo.com
 *
 */
public class LocalDateToZonedDateTimePSTExample {

	public static void main(String[] args) {

		// Creating LocalDate object
		LocalDate localDate = LocalDate.now();

		// Creating timezone with PST zone id. We can pass here any timezone id supported by java.
		ZoneId zoneid = ZoneId.of("US/Pacific");

		// LocalDate to PST zoneddatetime
		ZonedDateTime zonedDateTimeInPST = localDate.atStartOfDay(zoneid);

		System.out.println("localDate : " + localDate);
		System.out.println("ZonedDateTime in PST : " + zonedDateTimeInPST);
	}
}

Output:

localDate : 2020-12-07
ZonedDateTime in PST : 2020-12-07T00:00-08:00[US/Pacific]

4. Conclusion


In this article, We've seen the examples on how to convert LocalDate to ZonedDateTime in java 8 api.



Sunday, December 6, 2020

Java Convert LocalDate to LocalDateTime

1. Overview

In this tutorial, We'll learn how to convert LocalDate to LocalDateTime in java 8. LocalDate class stores only year, month and day. But, this does not store the time part and timezone. Whereas LocalDateTime holds the date and time part with naoseoncds.

You might have doubt by this time, how to convert the LocalDate to LocalDateTime because LocalDate is not having the time part but LocalDateTime does have. In order to convert localdate to localdatetime, we need to explicitly append the time part as needed.

This conversion can be done in two ways. Use atStartOfDay() or atTime() methods to append the time part to localdate and create a new LocalDateTime object.

Syntax:

public LocalDateTime atStartOfDay()

public LocalDateTime atTime(int hour, int minute)
public LocalDateTime atTime(int hour,
                            int minute,
                            int second)
public LocalDateTime atTime(int hour,
                            int minute,
                            int second,
                            int nanoOfSecond)							
public LocalDateTime atTime(LocalTime time)

Java Convert LocalDate to LocalDateTime


2. LocalDate to LocalDateTime using atStartOfDay() - Start Of Day


First we will look at atStartOfDay() method and how conversion is done into LocalDateTime with time part because this method is not taking any argument.

atStartOfDay() method combines localdate with the time of midnight to create a LocalDateTime at the start of this date.

This method returns a LocalDateTime formed from this date at the time of midnight, 00:00, at the start of this date.

package com.javaprogramto.java8.dates.localdate;

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

/**
 * 
 * Example to convert from LocalDate to LocalDateTime using atStartOfDay() method.
 * 
 * @author javaprogramto.com
 *
 */
public class LocalDateAtStartOfDayExample {

	public static void main(String[] args) {
		
		// creating localdate object
		LocalDate localDate = LocalDate.now();
		
		// Getting the LocalDateTime from LocalDate with atStartOfDay()
		LocalDateTime localDateTime = localDate.atStartOfDay();
		
		// printing the dates
		System.out.println("LocalDate : "+localDate);
		System.out.println("LocalDateTime : "+localDateTime);
	}
}

Output:
LocalDate : 2020-12-06
LocalDateTime : 2020-12-06T00:00

From the above output, we can see that Localdatetime is appended with hours and minutes as 00. That is LocalDateTime object is set to the start of LocalDate. This method is useful if you want to just convert LocalDate to LocalDateTime with time part as 0.


3. LocalDate to LocalDateTime using atTime() 


Next, Let us look at another method atTime() with time parameters. atTime() method is an overloaded method with different type of time arguments.

atTime() method combines this date with a time to create a LocalDateTime. The returned LocalDateTime object is added with the given time values.  But there is another overloaded method that returns ZonedLocalDate.

hour - the hour-of-day to use, from 0 to 23
minute - the minute-of-hour to use, from 0 to 59
second - the second-of-minute to represent, from 0 to 59

package com.javaprogramto.java8.dates.localdate;

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

public class LocalDateToLocalDateTimeAtTimeExample {

	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. Remaining parts are set to 0.
		LocalDateTime dateAndTime1 = localDate.atTime(hour, minute);

		// this produces the output as same as atStartOfDay()
		LocalDateTime dateAndTime2 = localDate.atTime(0, 0);

		// with custom time parts
		LocalDateTime dateAndTime3 = localDate.atTime(hour, minute, second);
		
		// From LocalTime
		LocalDateTime dateAndTime4 = localDate.atTime(LocalTime.now());

		// printing the LocalDateTime values
		System.out.println("LocalDate : " + localDate);
		System.out.println("LocalDateTime with hour, minute : " + dateAndTime1);
		System.out.println("LocalDateTime with hour minute as 00 : " + dateAndTime2);
		System.out.println("LocalDateTime with hour, minute, second : " + dateAndTime3);
		System.out.println("LocalDateTime 4 with LocalTime including nano seconds : " + dateAndTime4);
	}
}

Output:

LocalDate : 2020-12-06
LocalDateTime with hour, minute : 2020-12-06T10:20
LocalDateTime with hour minute as 00 : 2020-12-06T00:00
LocalDateTime with hour, minute, second : 2020-12-06T10:20:30
LocalDateTime 4 with LocalTime including nano seconds : 2020-12-06T23:33:53.337752


4. Conclusion


In this article, we've seen how to convert LocalDate to LocalDateTime in java 8 date time api and shown the example programs in 2 ways.



Java String split() Examples on How To Split a String With Different Delimiters

1. Overview


As part of String API features series, You'll learn how to split a string in java and also how to convert a String into String array for a given delimiter

This concept looks easy but quite a little tricky. You'll understand this concept clearly after seeing all the examples on the split() method.

The string split() method breaks a given string around matches of the given regular expression.
Java String split() Examples on How To Split a String

Java LocalDate compareTo() Example

1. Overview

In this tutorial, We'll learn how to use compareTo() method of LocalDate class in java 8.

compareTo() method is part of new date time api. This method is used to check if the date1 is before date2 or date1 is after date 2 or date1 and date 2 are equals.

Syntax:
public int compareTo(ChronoLocalDate other)

This method takes any object that implements ChronoLocalDate interface. ChronoLocalDate interface implementations are HijrahDate, JapaneseDate, LocalDate, MinguoDate, ThaiBuddhistDate.

This method returns 0 if both the dates are equal.
This method returns positive value if “this date” is greater than the otherDate.
This method returns negative value if “this date” is less than the otherDate.

Java LocalDate compareTo() Example



2. Java 8 LocalDate.compareTo() Example


Example program on to understand the compareTo() method of LocalDate class.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

/**
 * Java 8 LocalDate.compareTo() method examples
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateCompareToExample {

	public static void main(String[] args) {

		// Creating two LocalDate date objects using now() method
		LocalDate localDate1 = LocalDate.now();
		LocalDate localDate2 = LocalDate.now();

		// printing localDate1 and localDate2
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDate2 : " + localDate2);

		// calling compareTo() method on two local dates
		int compareToResult = localDate1.compareTo(localDate2);

		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate1 and localDate2 are same");
		} else if (compareToResult == 1) {
			System.out.println("localDate1 is after localDate2 ");
		} else {
			System.out.println("localDate1 is before localDate2 ");
		}

		// Creating another two LocalDate date objects using of() method with different
		// dates
		LocalDate localDate3 = LocalDate.of(2025, 01, 01);
		LocalDate localDate4 = LocalDate.of(2030, 01, 01);

		// printing localDate3 and localDate4
		System.out.println("\nlocalDate3 : " + localDate3);
		System.out.println("localDate4 : " + localDate4);

		// calling compareTo() method on two local dates
		compareToResult = localDate3.compareTo(localDate4);

		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate3 and localDate4 are same");
		} else if (compareToResult == 1) {
			System.out.println("localDate3 is after localDate4 ");
		} else {
			System.out.println("localDate3 is before localDate4 ");
		}
	}
}
Output:
localDate1 : 2020-12-06
localDate2 : 2020-12-06
localDate1 and localDate2 are same

localDate3 : 2025-01-01
localDate4 : 2030-01-01
localDate3 is before localDate4 

3. compareTo() method with different Date Time Type Objects


In the previous example compared two LocalDate objects with same and different values.

Now, compare LocalDate with MinguoDate objects using compareTo() objects.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.chrono.MinguoDate;

/**
 * Java 8 LocalDate.compareTo() method examples with MinguoDate
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateCompareToWithMinguoDate {

	public static void main(String[] args) {

		// Creating LocalDate date objects using now() method
		LocalDate localDate = LocalDate.now();
		
		// Creating MinguoDate date objects using now() method
		MinguoDate minguoDate = MinguoDate.now();

		// printing localDate and minguoDate
		System.out.println("localDate : " + localDate);
		System.out.println("minguoDate : " + minguoDate);

		// calling compareTo() method on two local dates
		int compareToResult = localDate.compareTo(minguoDate);

		// Printing output of compareTo() method
		System.out.println("compareToResult : "+compareToResult);
		
		// LocalDate equals example
		if (compareToResult == 0) {
			System.out.println("localDate and minguoDate are same");
		} else if (compareToResult > 0) {
			System.out.println("localDate is after minguoDate ");
		} else {
			System.out.println("localDate is before minguoDate ");
		}
	}
}
Output:
localDate : 2020-12-06
minguoDate : Minguo ROC 109-12-06
compareToResult : -4
localDate is before minguoDate 

From the above example, we have passed the MinguoDate object to the compareTo() method and returned negative value. localdate value is before minguo date.

LocalDate.compareTo() method works with the different type of date objects and sub implementation of ChronoLocalDate interface only example with MinguoDate.


4. Conclusion


In this article, we've seen the usage of compareTo() method of LocalDate class with passing the arguments LocalDate and MinguoDate.


Java LocalDate equals() Example

1. Overview

In this tutorial, We'll learn how to compare two dates in java 8 using LocalDate.equals() method. equals() method returns a boolean value if the dates are same , it returns true else false.

Syntax:
public boolean equals(Object obj)

equals() method compares two dates contents in detail with year, month and day values. If any one of these values are not matched then it consider as these two dates are not equal. 
This method takes Object type argument. This object type should be LocalDate and then only these objects are compared otherwise it returns false directly.

Java LocalDate – equals() Example


2. Java 8 LocalDate.equals() Example


Example program to compare two LocalDate objects in java 8 with the help of equals() method.

Read the inline comments in the below program for better understanding.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;

/**
 * Java 8 LocalDate.equals() method examples
 * 
 * @author javaprograto.com
 *
 */

public class LocalDateEqualsExample {

	public static void main(String[] args) {

		// Creating two LocalDate date objects using now() method
		LocalDate localDate1 = LocalDate.now();
		LocalDate localDate2 = LocalDate.now();

		// printing localDate1 and localDate2
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDate2 : " + localDate2);

		// LocalDate equals example
		if (localDate1.equals(localDate2)) {
			System.out.println("localDate1 and localDate2 are same");
		} else {
			System.out.println("localDate1 and localDate2 are not same");
		}

		// Creating another two LocalDate date objects using of() method with different dates
		LocalDate localDate3 = LocalDate.of(2025, 01, 01);
		LocalDate localDate4 = LocalDate.of(2030, 01, 01);

		// printing localDate3 and localDate4
		System.out.println("\nlocalDate3 : " + localDate3);
		System.out.println("localDate4 : " + localDate4);

		// LocalDate equals example
		if (localDate3.equals(localDate4)) {
			System.out.println("localDate3 and localDate24 are same");
		} else {
			System.out.println("localDate3 and localDate4 are not same");
		}
	}
}

Output:
localDate1 : 2020-12-06
localDate2 : 2020-12-06
localDate1 and localDate2 are same

localDate3 : 2025-01-01
localDate4 : 2030-01-01
localDate3 and localDate4 are not same

3. Conclusion


In this article, we've seen how to use equals() method of LocalDate class in new datetime api in java 8 with example programs.

If we pass the LocalDateTime object to this equals() method then it returns false because internal implementation checks the given instance is type of LocalDate. If we pass LocalDateTime object, instance type check becomes false.

Alternative to this method, We can use the LocalDate.compareTo() method which compares the dates but compareTo() returns integer value rather than boolean.



Saturday, December 5, 2020

Java Program To Check Palindrome String Using Recursion

1. Overview

In this tutorial, We'll learn how to check the string is palindrome using Recursive function in java.

String palindrome means if the string reversed value is equal to the original string.

Recursion means calling the one function from the same function. This is a computer programming concept and it is implemented in java.

Java Program To Check Palindrome String Using Recursion


2. Java String Palindrome Recursive example

Below example code is implemented using recursion approach. In that isPalindrome() method is getting called from the same method with substring value of original string.

Example: 

Step 1: Input string is : madam

Step 2: First call to isPalindrome("madam") - first and last character is same -> m == m -> true

Step 3: Next, calling the same isPalindrome("ada") with "ada" - first and last character same -> a == a -> true

Step 4: Next, again calling the same method isPalindrome() with "d" value. Now the first if condition checks that length of this string is 1 so it returns true. This value passed to the previous step where input is "ada".

Step 5: Again from "ada" call returns true value to "madam" input call. So, finally it returns true to the main method.

All of these methods are placed inside a Runtime Stack and will be called back from top.

If the input is 1234, first and last character is not same so it comes to final return false. Hence, the string 1234 is not a palindrome.

package com.javaprogramto.programs.strings;

public class StringPalindromeRecursiveExample {

	public static void main(String[] args) {
		// input string 1234
		String string = "1234";
		/*
		 * If function returns true then the string is palindrome otherwise not
		 */
		if (isPalindrome(string))
			System.out.println(string + " is a palindrome");
		else
			System.out.println(string + " is not a palindrome");

		// input string 1234
		String string2 = "madam";
		/*
		 * If function returns true then the string is palindrome otherwise not
		 */
		if (isPalindrome(string2))
			System.out.println(string2 + " is a palindrome");
		else
			System.out.println(string2 + " is not a palindrome");

	}

	/**
	 * Recursive function to check the string is palindrome or not.
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isPalindrome(String s) {

		// if the string has one or zero characters then recursive call is stopped.
		if (s.length() == 0 || s.length() == 1)
			return true;

		// checking the first and last character of the string. if equals then call the
		// same function with substring from index 1 to length -1. Because substring
		// excludes the endIndex.
		// if these two values are not same then string is not Palindrome so this
		// returns false.
		if (s.charAt(0) == s.charAt(s.length() - 1))
			return isPalindrome(s.substring(1, s.length() - 1));

		// this statment is executed if and if only first and last character of string
		// at any time is not equal.
		return false;
	}
}


Output:

1234 is not a palindrome
madam is a palindrome


3. Conclusion

In this article, we've seen how to check the string is palindrome or not using recursive method in java.

GitHub

Friday, December 4, 2020

Converting Between LocalDate and SQL Date In Java 8

1. Overview

In this tutorial, We'll learn how to convert java.time.LocalDate to java.sql Date in java 8 and vice versa.

This is simple to do but when working jpa framework it is bit different to deal with the table column type.

First look at the simple conversions between LocalDate and sql Date objects in java. Next, look at the JPA problem.

Converting Between LocalDate and SQL Date In Java 8


2. Direction conversion between LocalDate and SQL Date


2.1 Convert LocalDate to SQL Date


Use direct method from sql Date.valueOf() method which takes the LocalDate object. So, We can pass the object of LocalDate.now() or LocalDate.of() method.

Look at the below example.
package com.javaprogramto.java8.dates.conversion.sql;

import java.sql.Date;
import java.time.LocalDate;

public class LocalDateToSQLDateExample {

	public static void main(String[] args) {

		// creating current local date using now() method and which will return the
		// curren date.
		LocalDate currentDate = LocalDate.now();

		// LocalDate to SQL date using valueOf() method.
		Date sqlDate = Date.valueOf(currentDate);

		// printing
		System.out.println("With current local date");
		System.out.println("LocalDate : " + currentDate);
		System.out.println("SQL Date : " + sqlDate);
		
		// working with different dates.
		LocalDate pastDate = LocalDate.of(1990, 01, 01);
		LocalDate futureDate = LocalDate.of(2050, 01, 01);
		
		// converting Local dates to sql dates
		Date pastSqlDate = Date.valueOf(pastDate);
		Date futureSqlDate = Date.valueOf(futureDate);
		
		System.out.println("\nWith different local dates");
		System.out.println("Past LocalDate : " + pastDate);
		System.out.println("Past SQL Date : " + pastSqlDate);
		
		System.out.println("Future LocalDate : " + futureDate);
		System.out.println("Future SQL Date : " + futureSqlDate);
	}
}
Output:
With current local date
LocalDate : 2020-12-04
SQL Date : 2020-12-04

With different local dates
Past LocalDate : 1990-01-01
Past SQL Date : 1990-01-01
Future LocalDate : 2050-01-01
Future SQL Date : 2050-01-01

If null value is passed to the Date.valueOf() method, it will throw NullPointerException.
LocalDate nullLocalDate = null;
Date nullDate = Date.valueOf(nullLocalDate);

Output:
Exception in thread "main" java.lang.NullPointerException
	at java.sql/java.sql.Date.valueOf(Date.java:291)
	at com.javaprogramto.java8.dates.conversion.sql.LocalDateToSQLDateExample.main(LocalDateToSQLDateExample.java:38)


2.2 Convert SQL Date to LocalDate


Use toLocalDate() method to convert sql date to time LocalDate in java 8.
package com.javaprogramto.java8.dates.conversion.sql;

import java.sql.Date;
import java.time.LocalDate;

public class SQLDateToLocalDateExample {

	public static void main(String[] args) {

		// Creating sql date
		Date sqlDate = Date.valueOf("2020-12-31");
		
		// converting sql date to localdate using toLocalDate() method.
		LocalDate localDate1 = sqlDate.toLocalDate();

		// printing the local date.
		System.out.println("Local Date 1 : "+localDate1);
	}
}

Output:
Local Date 1 : 2020-12-31

3. JPA Problem Solving AttributeConverter


If you are using the LocalDate as column type in the JPA entity and this is should be having some mapping to the the database columns type. For this type, we assume that sql Date is the right one for the column type. But, database can not recognize the type LocalDate and JPA will map this to blob type rather than java sql Date object.

This is the problem now. To solve this, we should tell to JPA that if there is any column with LocalDate type, convert it into java.sql.Date when inserting into database and convert sql date to LocalDate while retrieving the records from database.

Java persistence api is added with AttributeConverter interface in jdk 1.7.

We need to implement AttributeConverter interface and need to specify the input object type and converted result object type.

This interface has two abstract methods convertToDatabaseColumn() and convertToEntityAttribute().

convertToDatabaseColumn() is to convert the LocalDate to sql date and saves into database.
convertToEntityAttribute() method is executed when fetching the records from database and converts into LocalDate.

We have used Optional inside these two methods to better handle null references to avoid null pointer exception.
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;
import java.util.Optional;

@Converter(autoApply = true)
public class LocalDateConverterExample implements AttributeConverter<LocalDate, Date> {


	// converts LocalDate to sql date using valueOf() method
    @Override
    public Date convertToDatabaseColumn(LocalDate localDate) {
        return Optional.ofNullable(localDate)
          .map(Date::valueOf)
          .orElse(null);
    }

	// converts sql date to LocalDate using toLocalDate() method
    @Override
    public LocalDate convertToEntityAttribute(Date date) {
        return Optional.ofNullable(date)
          .map(Date::toLocalDate)
          .orElse(null);
    }
}


Observe the above code, We've used the @Converter annotation with element autoApply to true. That means apply this conversion is applied to all targeted types by the persistence provider.

But by default this property autoApply is set to false.

If there is more than one converter defined for the same target type, the Convert annotation should be used to explicitly specify which converter to use.

4. Conclusion


In this article, We've seen how to convert between LocalDate and SQL Date in java with example programs.

And also shown how to solve the LocalDate type problem in JPA framework using AttributeConverter interface and @Converter annotation.



Java 8 Stream forEach With Index

1. Overview

In this tutorial, We'll learn how to print the index when using java 8 forEach with streams.

In real-time when working with list.stream().forEach() method, it does not allow to use the index variable which is declared outside lambda expression.  If we declare the variable inside lambda then it will be reset to the initial value again. So, it is not possible and there are limitations while accessing the variables from inside lambda expressions

Let us explore the ways to get the indices when using forEach method on streams.

First, We'll show the example using Arrays and next on the List of String objects. Getting the index value or number can be addressed with IntStream.range() method.

Java 8 Stream forEach With Index