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.