Java 8 – TemporalAdjusters examples

In Java 8, you can use the predefined java.time.temporal.TemporalAdjusters to adjust a date or Temporal 1. TemporalAdjusters Example to move a date to firstDayOfMonth, firstDayOfNextMonth, next Monday and etc. TestDate.java package com.mkyong.time; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; public class TestDate { public static void main(String[] args) { LocalDate localDate = LocalDate.now(); System.out.println("current date : …

Read more

Java 8 – Period and Duration examples

Few examples to show you how to use Java 8 Duration, Period and ChronoUnit objects to find out the difference between dates. Duration – Measures time in seconds and nanoseconds. Period – Measures time in years, months and days. 1. Duration Example A java.time.Duration example to find out difference seconds between two LocalDateTime DurationExample.java package …

Read more

Java 8 – How to format LocalDateTime

Few examples to show you how to format java.time.LocalDateTime in Java 8. 1. LocalDateTime + DateTimeFormatter To format a LocalDateTime object, uses DateTimeFormatter TestDate1.java package com.mkyong.time; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class TestDate1 { public static void main(String[] args) { //Get current date time LocalDateTime now = LocalDateTime.now(); System.out.println("Before : " + now); DateTimeFormatter formatter …

Read more

Java 8 – HijrahDate, How to calculate the Ramadan date

Ramadan is the 9th month of the Islamic calendar, the entire month. 1. HijrahDate -> Ramadan 2016 Full example to calculate the start and end of the Ramadan 2016 TestHijrahDate.java package com.mkyong.date; import java.time.LocalDate; import java.time.chrono.HijrahDate; import java.time.temporal.ChronoField; import java.time.temporal.TemporalAdjusters; public class TestDate { public static void main(String[] args) { //first day of Ramadan, 9th …

Read more

Java 8 – MinguoDate examples

This MinguoDate calendar system is primarily used in Taiwan (Republic of China…) (ISO) 1912-01-01 = 1-01-01 (Minguo ROC) To convert the current date to the Minguo date, just subtracts the current year with number 1911, for example 2016 (ISO) – 1911 = 105 (Minguo ROC) 1. LocalDate -> MinguoDate Review a full example to convert …

Read more

Java 8 – ZonedDateTime examples

Few Java 8 java.time.ZonedDateTime examples to show you how to convert a time zone between different countries. Table of contents 1. Convert LocalDateTime to ZonedDateTime 2. Malaysia (UTC+08:00) -> Japan (UTC+09:00) 3. France, Paris (UTC+02:00, DST) -> (UTC-05:00) 4. References 1. Convert LocalDateTime to ZonedDateTime The LocalDateTime has no time zone; to convert the LocalDateTime …

Read more

Java 8 – Convert Date to LocalDate and LocalDateTime

Here is the code to convert java.util.Date to java.time.LocalDate. Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // different way of create instant object LocalDate localDate = Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); Convert java.util.Date to java.time.LocalDateTime. Date date = new Date(); LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); Convert java.util.Date to java.time.ZonedDateTime. Date date = new Date(); ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault()); …

Read more

Java 8 – Convert Instant to ZonedDateTime

Java 8 examples to show you how to convert from Instant to ZonedDateTime 1. Instant -> ZonedDateTime Example to convert a Instant UTC+0 to a Japan ZonedDateTime UTC+9 InstantZonedDateTime1.java package com.mkyong.date; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class InstantZonedDateTime1 { public static void main(String[] argv) { // Z = UTC+0 Instant instant = Instant.now(); …

Read more

Java 8 – Convert Instant to LocalDateTime

Java 8 examples to show you how to convert from Instant to LocalDateTime 1. Instant -> LocalDateTime The java.time.LocalDateTime has no concept of time zone, just provide a zero offset UTC+0. InstantExample1.java package com.mkyong.date; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; public class InstantExample1 { public static void main(String[] argv) { // Parse a ISO 8601 …

Read more

Java – Display all ZoneId and its UTC offset

A Java 8 example to display all the ZoneId and its OffSet hours and minutes. P.S Tested with Java 8 and 12 1. Display ZoneId and Offset DisplayZoneAndOffSet.java package com.mkyong; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class DisplayZoneAndOffSet { public static final boolean SORT_BY_REGION = false; …

Read more

Java 8 – How to convert String to LocalDate

Here are a few Java examples of converting a String to the new Java 8 Date API – java.time.LocalDate DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); String date = "16/08/2016"; //convert String to LocalDate LocalDate localDate = LocalDate.parse(date, formatter); The key is understand the DateTimeFormatter patterns Note You may interest at this classic java.util.Date example – How to …

Read more

Java 8 – How to sort a Map

Java 8 Stream examples to sort a Map, by keys or by values. 1. Quick Explanation Steps to sort a Map in Java 8. Convert a Map into a Stream Sort it Collect and return a new LinkedHashMap (keep the order) Map result = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); P.S By …

Read more

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList Java8Example1.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example1 { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node"); //Convert a Stream to List List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output …

Read more

Java 8 – Filter a null value from a Stream

Review a Stream containing null values. Java8Examples.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Examples { public static void main(String[] args) { Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php"); List<String> result = language.collect(Collectors.toList()); result.forEach(System.out::println); } } output java python node null //

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

Java 8 flatMap example

This article explains the Java 8 Stream.flatMap and how to use it. Topic What is flatMap? Why flat a Stream? flatMap example – Find a set of books. flatMap example – Order and LineItems. flatMap example – Splits the line by spaces. flatMap and Primitive type 1. What is flatMap()? 1.1 Review the below structure. …

Read more

Java – How to convert Array to Stream

In Java 8, you can either use Arrays.stream or Stream.of to convert an Array into a Stream. 1. Object Arrays For object arrays, both Arrays.stream and Stream.of returns the same output. TestJava8.java package com.mkyong.java8; import java.util.Arrays; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { String[] array = {"a", "b", "c", "d", …

Read more

Java – Stream has already been operated upon or closed

In Java 8, Stream cannot be reused, once it is consumed or used, the stream will be closed. 1. Example – Stream is closed! Review the following example, it will throw an IllegalStateException, saying “stream is closed”. TestJava8.java package com.mkyong.java8; import java.util.Arrays; import java.util.stream.Stream; public class TestJava8 { public static void main(String[] args) { String[] …

Read more

Java 8 – Stream Collectors groupingBy examples

In this article, we will show you how to use Java 8 Stream Collectors to group by, count, sum and sort a List. 1. Group By, Count and Sort 1.1 Group by a List and display the total count of it. Java8Example1.java package com.mkyong.java8; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public …

Read more

Java 8 – Convert List to Map

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys. Hosting.java package com.mkyong.java8 public class Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites …

Read more

Java 8 Streams filter examples

In this tutorial, we will show you few Java 8 examples to demonstrate the use of Streams filter(), collect(), findAny() and orElse() 1. Streams filter() and collect() 1.1 Before Java 8, filter a List like this : BeforeJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeJava8 { public static void main(String[] args) …

Read more

Java 8 – StringJoiner example

In this article, we will show you a few StringJoiner examples to join String. 1. StringJoiner 1.1 Join String by a delimiter StringJoiner sj = new StringJoiner(","); sj.add("aaa"); sj.add("bbb"); sj.add("ccc"); String result = sj.toString(); //aaa,bbb,ccc 1.2 Join String by a delimiter and starting with a supplied prefix and ending with a supplied suffix. StringJoiner sj …

Read more

Java 8 Stream – Read a file line by line

In Java 8, you can use Files.lines to read file as Stream. c://lines.txt – A simple text file for testing line1 line2 line3 line4 line5 1. Java 8 Read File + Stream TestReadFile.java package com.mkyong.java8; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class TestReadFile { public static void main(String args[]) { String fileName …

Read more

Java 8 Lambda : Comparator example

In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List. 1. Classic Comparator example. Comparator<Developer> byName = new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); } }; 2. Lambda expression equivalent. Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()); …

Read more