Java 8 – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 21 Nov 2023 08:41:46 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java 8 – Java2Blog https://java2blog.com 32 32 [Fixed] Unable to obtain LocalDateTime from TemporalAccessor https://java2blog.com/unable-to-obtain-localdatetime-from-temporalaccessor/?utm_source=rss&utm_medium=rss&utm_campaign=unable-to-obtain-localdatetime-from-temporalaccessor https://java2blog.com/unable-to-obtain-localdatetime-from-temporalaccessor/#respond Sat, 19 Feb 2022 18:58:49 +0000 https://java2blog.com/?p=19467 In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8.

Unable to obtain LocalDateTime from TemporalAccessor : Reason

You will generally get this error, when you try to convert String to LocalDateTime and Formatted String does not have time related information.

Let’s understand with the help of example:

package org.arpit.java2blog;

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

public class StringToLocalDateTime {

    public static void main(String[] args) {

        // Custom formatted String
        String dateStr = "2022-02-16";

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // Convert String to LocalDateTime using Parse() method
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormatter);

        // Print LocalDateTime object
        System.out.println("LocalDateTime obj: "+localDateTime);
    }
}

Output:=

Exception in thread "main" java.time.format.DateTimeParseException: Text '2022-02-16' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2022-02-16 of type java.time.format.Parsed
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at org.arpit.java2blog.StringToLocalDateTime.main(StringToLocalDateTime.java:17)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2022-02-16 of type java.time.format.Parsed
    at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.base/java.time.format.Parsed.query(Parsed.java:235)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2022-02-16 of type java.time.format.Parsed
    at java.base/java.time.LocalTime.from(LocalTime.java:431)
    at java.base/java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more

Unable to obtain LocalDateTime from TemporalAccessor : Fix

LocalDate’s parse() method with atStartOfDay()

As Formatted String does not contain time information, we need to use LocalDate’s parse() method and call atStartOfDay() method to get LocalDateTime object.

package org.arpit.java2blog;

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

public class StringToLocalDateTime {

    public static void main(String[] args) {

        // Custom formatted String
        String dateStr = "2022-02-16";

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // Convert String to LocalDateTime using LocalDate's parse() method
        LocalDateTime localDateTime = LocalDate.parse(dateStr,dateTimeFormatter).atStartOfDay();

        // Print LocalDateTime object
        System.out.println("LocalDateTime obj: "+localDateTime);
    }
}

Output:

LocalDateTime obj: 2022-02-16T00:00

Use LocalDate instead of LocalDateTime

Since formatted String does not contain time information, we may want to use LocalDate rather than LocalDateTime.

We can use LocalDate’s parse() method to convert String to LocalDate in Java.

package org.arpit.java2blog;

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

public class StringToLocalDate {

    public static void main(String[] args) {
        // Custom formatted String
        String dateStr = "2022-02-16";

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // Convert String to LocalDateTime using LocalDate's parse() method
        LocalDate localDate = LocalDate.parse(dateStr,dateTimeFormatter);

        // Print LocalDateTime object
        System.out.println("LocalDate obj: "+localDate);
    }
}

Output:

LocalDate obj: 2022-02-16
]]>
https://java2blog.com/unable-to-obtain-localdatetime-from-temporalaccessor/feed/ 0
Convert LocalDate to Instant in Java https://java2blog.com/java-localdate-to-instant/?utm_source=rss&utm_medium=rss&utm_campaign=java-localdate-to-instant https://java2blog.com/java-localdate-to-instant/#respond Thu, 17 Feb 2022 11:49:11 +0000 https://java2blog.com/?p=19461 In this article, we will see how to convert LocalDate to Instant in Java.

Java LocalDate to Instant

Instant class provides an instantaneous point in time. When you want to convert LocalDate to Instant, you need to provide time zone.

Using toInstant() wth ZoneId

ZoneDateTime’s toInstant() method can be used to convert LocalDate to Instant. You need to provide ZoneId before doing the conversion.

  • Get LocalDate object with LocalDate.now()
  • Create ZoneId instance based on the Locale
  • Pass ZoneId to LocalDate‘s atStartOfDay() to get ZoneDateTime.
  • Use ZoneDateTime‘s toInstant() method to convert LocalDate to Instant in Java.

If you want to have default timezone, you can use ZoneId.systemDefault(). It will provide you default timezone of JVM.

package org.arpit.java2blog;

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

public class JavaLocalDateToInstant {

    public static void main(String[] args) {
        // Get LocalDate object
        LocalDate date = LocalDate.now();

        // Get default timezone
        ZoneId zoneId = ZoneId.systemDefault();

        // Convert LocalDate to Instant using toInstant() method
        Instant instant = date.atStartOfDay(zoneId).toInstant();

        // Print Instant
        System.out.println("Instant obj: "+instant);
    }
}

Output:

Instant obj: 2022-02-16T18:30:00Z

Using toInstant() with ZoneOffset

You can pass ZoneOffset to ZoneDateTime’s toInstant() method to convert LocalDate to Instant in Java.

package org.arpit.java2blog;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;

public class JavaLocalDateToInstant {

    public static void main(String[] args) {
        // Get LocalDate object
        LocalDate localDate = LocalDate.now();

        // Convert LocalDate to Instant with ZoneOffSet
        Instant instant = localDate.atStartOfDay().toInstant(ZoneOffset.UTC);

        // Print Instant
        System.out.println("Instant obj: "+instant);
    }
}

Output:

Instant obj: 2022-02-17T00:00:00Z

That’s all about how to convert LocalDate to Instant in Java.

]]>
https://java2blog.com/java-localdate-to-instant/feed/ 0
Convert Instant to LocalDate in Java https://java2blog.com/java-instant-to-localdate/?utm_source=rss&utm_medium=rss&utm_campaign=java-instant-to-localdate https://java2blog.com/java-instant-to-localdate/#respond Thu, 17 Feb 2022 10:50:32 +0000 https://java2blog.com/?p=19453 1. Overview

In this article, we will see how to convert Instant to LocalDate in java. An Instant represents a specific moment in time in the UTC timezone, whereas a LocalDate represents a date without time or timezone information. The challenge is to extract the date part from an Instant object and represent it as a LocalDate.

2. Introduction to Problem Statement

Let’s say we have an Instant representing "2023-11-21T15:30:00Z", the expected output as a LocalDate would be "2023-11-21". Our goal is to explore different methods to achieve this.

3. Using ofInstant method [ Java 9+]

Most straightforward way to convert instant to LocalDate is using LocalDate’s static method ofInstant() introduced in Java 9.

It takes Instant and ZoneId as input and returns LocalDate object.

public static LocalDate ofInstant(Instant instant,ZoneId zone)

Let’s see with the help of example:

// Create Instant object
Instant instant = Instant.parse("2022-01-23T00:00:00Z");

// Get ZoneID
ZoneId zone = ZoneId.of("Europe/London");

// Convert Instant to LocalDate using ofInstant method
LocalDate localDate = LocalDate.ofInstant(instant, zone);

// Print LocalDate
System.out.println("LocalDate Obj: "+localDate);

Output:

LocalDate Obj: 2022-01-23

LocalDate.ofInstant(Instant, ZoneId): Converts the Instant to LocalDate using the provided timezone.
ZoneId.systemDefault(): Uses the system’s default timezone for conversion.

This method is recommended for most use cases due to its simplicity and directness. It’s suitable for applications where the system’s default timezone is appropriate for the conversion.

4. Using ZoneDateTime’s toLocalDate() [Java 8]

  • Get Instant object which we want to convert to LocalDate.
  • Create ZoneId instance using ZoneId.systemDefault().
  • Pass ZoneId to atZone() method to get ZoneDateTime.
  • Call toLocalDate() on ZoneDateTime object to get LocalDate.
// Create Instant object
  Instant instant = Instant.parse("2022-01-23T00:00:00Z");

  // Convert to LocalDate using instant.atZone()
  LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();

  // Print LocalDate
  System.out.println("LocalDate Obj: "+localDate);

Output:

LocalDate Obj: 2022-01-23

instant.atZone(ZoneId): Attaches the timezone to the Instant, converting it to ZonedDateTime.
.toLocalDate(): Extracts the LocalDate part from the ZonedDateTime.

This method provides more control over the timezone used for conversion. It is particularly useful in scenarios where the timezone needs to be specified or adjusted.

5. Using Instant.toEpochMilli()

A less conventional method involves converting the Instant to epoch milliseconds and then to LocalDate.

Instant instant = Instant.now()
LocalDate localDate = new Date(instant.toEpochMilli())
                .toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
// Print LocalDate
System.out.println("LocalDate Obj: "+localDate);

instant.toEpochMilli(): Converts the Instant to milliseconds since the Unix epoch.
new Date(long): Constructs a Date object from the epoch milliseconds.
The rest of the process converts the Date back to Instant, then to ZonedDateTime, and finally extracts the LocalDate.

This method might be useful when dealing with legacy code that requires interoperation between Date and the newer Java Date-Time API. However, it is more convoluted and not recommended for general use.

6. Conclusion

Converting an Instant to a LocalDate in Java can be achieved through various methods.

The LocalDate.ofInstant() method is the most straightforward and is ideal for typical use cases.

The Instant.atZone() method offers additional control over the timezone and is beneficial when timezone manipulation is needed. The conversion through epoch milliseconds offers compatibility with legacy systems but is less direct and more complex.

]]>
https://java2blog.com/java-instant-to-localdate/feed/ 0
Convert String to LocalDateTime in Java https://java2blog.com/java-string-to-localdatetime/?utm_source=rss&utm_medium=rss&utm_campaign=java-string-to-localdatetime https://java2blog.com/java-string-to-localdatetime/#respond Wed, 16 Feb 2022 18:53:15 +0000 https://java2blog.com/?p=19432 In this article, we will see how to convert String to LocalDateTime in Java.

LocalDateTime class was introduced in Java 8. LocalDateTime represents local date and time without timezone information. It is represented in ISO 8601 format (yyyy-MM-ddTHH:mm:ss) by default.

Java String to LocalDateTime

To convert String to LocalDateTime in Java, LocalDateTime provides static method parse() which takes String as input and returns LocalDateTime object.

public static LocalDateTime parse(CharSequence text)

parse() method accepts a date time String in ISO-8601 by default.

package org.arpit.java2blog;

import java.time.LocalDateTime;

public class StringToLocalDateTime {

    public static void main(String[] args) {

        // ISO-8601 formatted String
        String dateStr = "2022-02-16T10:22:15";

        // Convert String to LocalDateTime using Parse() method
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr);

        // Print LocalDateTime object
        System.out.println("LocalDateTime obj: "+localDateTime);
    }
}

Output:

LocalDateTime obj: 2022-02-16T10:22:15

In case, if you provide String in any other format, it will throw DateTimeParseException.

package org.arpit.java2blog;

import java.time.LocalDateTime;

public class StringToLocalDateTime {

    public static void main(String[] args) {

        // ISO-8601 formatted String
        String dateStr = "2022-02-16 10:22:15";

        // Convert String to LocalDateTime using Parse() method
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr);

        // Print LocalDateTime object
        System.out.println("LocalDateTime obj: "+localDateTime);
    }
}

Output:

Exception in thread “main” java.time.format.DateTimeParseException: Text ‘2022-02-16 10:22:15’ could not be parsed at index 10
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:477)
at org.arpit.java2blog.StringToLocalDateTime.main(StringToLocalDateTime.java:13)

Convert String to LocalDateTime with custom format

To convert String to LocalDateTime with custom format, we can use DateTimeFormatter.

  • Create DateTimeFormatter instance with specified format
  • Pass date formatted String and DateTimeFormatter instance to LocalDateTime’s parse() method.
package org.arpit.java2blog;

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

public class StringToLocalDateTime {

    public static void main(String[] args) {

        // Custom formatted String
        String dateStr = "2022-02-16 10:22";

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Convert String to LocalDateTime using Parse() method
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormatter);

        // Print LocalDateTime object
        System.out.println("LocalDateTime obj: "+localDateTime);
    }
}

Output:

LocalDateTime obj: 2022-02-16T10:22

That’s all about how to convert String to LocalDateTime in Java.

]]>
https://java2blog.com/java-string-to-localdatetime/feed/ 0
Format LocalDateTime to String in Java https://java2blog.com/java-localdatetime-to-string/?utm_source=rss&utm_medium=rss&utm_campaign=java-localdatetime-to-string https://java2blog.com/java-localdatetime-to-string/#respond Wed, 16 Feb 2022 18:07:55 +0000 https://java2blog.com/?p=19414 In this article, we will see how to format LocalDateTime to String in java.

Java LocalDateTime To String

To format LocalDateTime to String, we can create DateTimeFormatter and pass it to LocalDateTime’s format() method.

public String format(DateTimeFormatter formatter)

Here are steps:

  • Get LocalDateTime instance
  • Create DateTimeFormatter instance with specified format
  • Pass above DateTimeFormatter to format() method to convert LocalDateTime to String in java.

Here is complete code:

package org.arpit.java2blog;

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

public class LocalDateTimeToStringMain {

    public static void main(String[] args) {
        // Get current LocalDateTime
        LocalDateTime currentLocalDateTime = LocalDateTime.now();

        // Create DateTimeFormatter instance with specified format
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Format LocalDateTime to String
        String formattedDateTime = currentLocalDateTime.format(dateTimeFormatter);

        System.out.println("Formatted LocalDateTime in String format : " + formattedDateTime);
    }
}

Output:

Formatted LocalDateTime in String format : 2022-02-16 18:31

DateTimeFormatter is immutable and thread safe, so you do not have to create new instance every time. It is recommended to declare DateTimeFormatter instance static constant.

Convert LocalDateTime to Time Zone ISO8601 String

In case, you are working with ISO 8601, then you can use LocalDateTime’s atZone() method to get ZoneDateTime object and use toString() method on ZoneDateTime to convert LocalDateTime to String in java.

LocalDateTime currentDateTime = LocalDateTime.now(); 
ZonedDateTime zdt = currentDateTime.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601Format = zdt.toString();
// Output : 2022-02-16T18:45:50.408934Z

Parse String to LocalDateTime

Similar to format(), LocalDateTime provides parse() method to convert String to LocalDateTime in Java.
Here is sample code:

// Date in String datatype
        String dateStr = "2022-02-16 18:45";

        // Create DateTimeFormatter instance
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // Use Parse method to convert it back to LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr,dateTimeFormatter);

That’s all about how to Format LocalDateTime to String in Java 8.

]]>
https://java2blog.com/java-localdatetime-to-string/feed/ 0
Java 8 – Find duplicate elements in Stream https://java2blog.com/find-duplicate-elements-in-stream-java/?utm_source=rss&utm_medium=rss&utm_campaign=find-duplicate-elements-in-stream-java https://java2blog.com/find-duplicate-elements-in-stream-java/#respond Sat, 16 Oct 2021 19:05:49 +0000 https://java2blog.com/?p=17346 Introduction

When working with a collection of elements in Java, it is very common to have duplicate elements, and Java provides different APIs that we can use to solve the problem.

Java 8 Stream provides the functionality to perform aggregate operations on a collection, and one of the operations includes finding duplicate elements.

In this tutorial, we will see how to find duplicate elements in Stream in Java 8.

Create a custom object named Employee with fields id, firstName, and lastName and generate AllArgsConstructor, toString(), equals() and hashcode() methods.

When generating equals() and hashCode() ensure that you use field id to ensure that objects with the same hashcode() are stored in the same bucket.

We will use Employee class in our examples to create custom objects in a collection and remove duplicate objects using a Stream.

package com.Java2Code;

import java.util.Objects;

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

    }
}
class Employee{
    private int id;
    private String firstName;
    private String lastName;

    public Employee(int id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

Using distinct()

Create a List of Strings and call the stream() method to return a Stream of our elements.

Call the distinct() method that returns a stream of the elements without duplicates.

Collect the elements to a List by calling the Collectors.toList() in the collect() method.

To view the duplicate elements, we just remove the elements in the new List from the original List, and we will be left with the duplicate elements.

package com.Java2Code;

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

public class FindDuplicateElementsUsingStream {
    public static void main(String[] args){
        List cars = new ArrayList<>(
                List.of(
                        "Mercedes",
                        "Toyota",
                        "Nissan",
                        "Volkswagen",
                        "Ford",
                        "Maclaren",
                        "Mercedes",
                        "Nissan",
                        "Ford"
                )
        );

        List distinctCars = cars.stream()
                .distinct()
                .collect(Collectors.toList());

        for (String distinctCar : distinctCars) {
            cars.remove(distinctCar);
        }

        cars.forEach(System.out::println);
    }
}

Output:

Mercedes

Nissan

Ford

Using Collections.frequency()

Create a List of employee objects and call the stream() method to return their a Stream.

Call the filter() method, which accepts a single input and returns a boolean.

The input to the filter() method will be a Collections.frequency(), which returns a boolean, and to enable this, we have to pass the list and the element we want to check and a condition to check whether the element occurs more than once.

The frequency() method uses the equals() method to compare the objects and that is why we generated a hashcode because two objects are equal if they have the same hashcode.

The frequency() method throws a NullPointerException if the provided collection is null.

Collect the duplicate objects to a Set using Collectors.toSet() in the collect() method.

package com.Java2Code;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class FindDuplicateElementsUsingStream {
    public static void main(String[] args){
        List employees = List.of(
                new Employee(1,"john","doe"),
                new Employee(2,"peter","parker"),
                new Employee(3,"mary","public"),
                new Employee(4,"charles","darwin"),
                new Employee(1,"john","doe"),
                new Employee(3,"mary","public")
        );

        Set duplicateEmployees = employees.stream()
                .filter(employee ->
                Collections.frequency(employees, employee) > 1)
                .collect(Collectors.toSet());

        duplicateEmployees.forEach(System.out::println);
    }
}

Output:

Employee{firstName=’john’, lastName=’doe’}
Employee{firstName=’mary’, lastName=’public’}

Using Collectors.toSet()

Create a List of String elements, a new HashSet that we will use to store the elements that are duplicates.

The default implementation of a Set does not support duplicate values, and adding a duplicate element leaves it unchanged and returns false.

Note that when you try to add a null element to the Set, it will throw a NullPointerException, and when an element is added successfully, it returns true, showing that it was not present in the Set.

Call the stream() method from the list, we just created to return a Stream of the elements.

Add a filter() method which filters elements which are not added to the Set and collects them to a Set using Collectors.toSet() method.

package com.Java2Code;

import java.util.*;
import java.util.stream.Collectors;

public class FindDuplicateElementsUsingStream {
    public static void main(String[] args){
        List languages = List.of(
                "english",
                "chinese",
                "french",
                "spanish",
                "hindi",
                "english",
                "french"
        );
        Set uniqueLanguages = new HashSet<>();
        Set duplicateLanguages = languages.stream()
                .filter(language -> !uniqueLanguages.add(language))
                .collect(Collectors.toSet());

        duplicateLanguages.forEach(System.out::println);
    }
}

Output:

english

french

Using Collectors.toMap()

The Collectors.toMap() method returns a Map, and we can find the duplicate elements by counting the number of occurrences of the input arguments and storing them as values in the Map.

To achieve this, we need to pass a keyMapper, valueMapper and a mergingFunction to the method.

The keyMapper is a Function that we will use to produce the keys by using Function.identity(), which returns the input arguments.

The valueMapper is a Function that we will use to produce the values by using computer -> 1, which returns 1 for each occurrence.

The Integer::sum is a BinaryOperator representing our merging function that will perform an addition operation each time a 1 is returned when a duplicate of the mapped keys is found.

The result of the merge function will be stored as our values in the Map, and this will help us to identify the duplicate elements in a Stream though it does not provide us with the capability to remove them.

package com.Java2Code;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FindDuplicateElementsUsingStream {
    public static void main(String[] args){
         List computers = List.of(
                "Dell",
                "HP",
                "IBM",
                "Apple",
                "HP",
                "Apple"
        );

        Map computerOccurrences = computers.stream()
                .collect(Collectors
                .toMap(Function.identity(), computer -> 1, Integer::sum));

        System.out.println(computerOccurrences);
    }
}

Output:

{Dell=1, Apple=2, IBM=1, HP=2}

Using Collectors.groupingBy()

The Collectors.groupingBy() method groups elements based on a classification function and returns the result in a Map.

The Map keys are a result of applying the classification function to the input elements, and the values contain the input elements, which map to the associated key under the classification function.

To achieve this we have to pass Function.identity() and Collectors.counting() respectively to the groupingBy().

Call entrySet() to return a Set view of the Map and use the stream() method again to filter the values that have a value greater than one using the filter() method.

Add a map() method and pass Map.Entry::getKey, which returns a Stream of the elements that are duplicate and collect the result to a set using the Collectors.toSet() method.

package com.Java2Code;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FindDuplicateElementsUsingStream {
    public static void main(String[] args){
        List employees = List.of(
                new Employee(1,"john","doe"),
                new Employee(2,"peter","parker"),
                new Employee(3,"mary","public"),
                new Employee(4,"charles","darwin"),
                new Employee(1,"john","doe"),
                new Employee(3,"mary","public")
        );

        Set duplicateEmployees= employees.stream()
                .collect(Collectors
                .groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .filter(employee -> employee.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());

        duplicateEmployees.forEach(System.out::println);
    }
}

Output:

Employee{firstName=’john’, lastName=’doe’}
Employee{firstName=’mary’, lastName=’public’}

Conclusion

In this tutorial, you have learned how to find duplicate elements using Java 8 elements using dinstinct(), frequency(), Collectors.toSet(), Collectors.toMap(), and Collectors.groupingBy() methods.

]]>
https://java2blog.com/find-duplicate-elements-in-stream-java/feed/ 0
How to Format Instant to String in Java https://java2blog.com/format-instant-to-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=format-instant-to-string-java https://java2blog.com/format-instant-to-string-java/#respond Sun, 02 May 2021 05:41:59 +0000 https://java2blog.com/?p=14076 1. Introduction

In Java, dealing with date and time is a common requirement in many applications. One specific task is formatting an Instant object to a String. An Instant represents a specific moment on the timeline in UTC. The goal is to convert this Instant into a human-readable date and time format as a String.

In this article, we will explore various methods to format an Instant to String in Java, compare their usability, and detail each approach to cover different scenarios.

2. Using DateTimeFormatter Class

Instant does not contain time zone information, it only have timestamp to milliseconds from UNIX epoch i.e 1 Jan 1970 from UTC,so DateTimeFormatter can not print date directly because date is always printed with time zone information.

In order to format Instant to String, we need to first associate timezone to formatter and it will work fine.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                                                        .withZone(ZoneId.systemDefault());
Instant instant = Instant.now();
String instantStr = formatter.format( instant );
System.out.println("Instant in String format: "+instantStr);

Output:

Instant in String format: 2023-11-21 12:30:19

DateTimeFormatter.ofPattern(String): Defines the pattern to format the date and time.
.withZone(ZoneId): Sets the time zone to use, here the system’s default time zone.
formatter.format(Instant): Formats the given Instant according to the defined pattern and time zone.

This method is versatile and recommended for most use cases, especially where custom date-time formats are required.

If we do not provide timezone information, then DateTimeFormatter will through an Exception.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

Instant instant = Instant.now();
String instantStr = formatter.format(instant);
System.out.println("Instant in String format: "+instantStr);

Output:

Exception in thread “main” java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.base/java.time.Instant.getLong(Instant.java:603)
at java.base/java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:308)
at java.base/java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2704)
at java.base/java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2343)
at java.base/java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1848)
at java.base/java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1822)
at org.arpit.java2blog.entry.FormatInstantToString.main(FormatInstantToString.java:15)

2.1 Using DateTimeFormatter in ISO-8601 format

We can use DateTimeFormatter with ISO_LOCAL_DATE_TIME to print String in ISO-8601 format.

DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
                                                       .withZone(ZoneId.from(ZoneOffset.UTC));

Instant instant = Instant.now();
String instantStr = formatter.format(instant);
System.out.println("Instant in String format: "+instantStr);

Output:

Instant in String format: 2021-05-01T12:06:04.970468

3. Using Instant’s toString() Method

Instants are already in UTC and if we are not worried about format, then we can simply use toString() method. Instant’s toString() method converts the Instant to an ISO-8601 string representation.

Instant instant = Instant.now();
String instantStr = instant.toString();
System.out.println("Default String format for Instant: "+instantStr);

Output:

Default String format for Instant: 2021-05-01T12:10:55.412386200Z

if we don’t want T and Z in the String. we can change highlighted line to:

String instantStr = instant.toString().replaceAll("[TZ]", " ");
// Output: Default String format for Instant: 2021-05-01 12:14:30.687870800

If we need time in milliseconds rather than nanosecond, we can use:

String instantStr = instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
// Output: Default String format for Instant: 2021-05-01 12:15:12.073

This method is straightforward and useful when the ISO-8601 format is acceptable. It requires no additional formatting.

4. Using Date.from(Instant) and SimpleDateFormat

The idea is to convert Instant to java.util.Date using Date.from(Instant) and then format it using SimpleDateFormat.

Instant instant = Instant.now();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = Date.from(instant);
System.out.println(sdf.format(date));
// Output : 2023-11-21 12:31:38

This method is suitable for applications that still use the older java.util.Date class, providing a bridge between the old and new Date-Time APIs.

5. Conclusion

Formatting an Instant to a String in Java can be achieved through various methods, each serving different needs.

The DateTimeFormatter approach is the most flexible and aligns with the modern Java Date-Time API, making it the preferred choice. The built-in toString() method of Instant is convenient for standard ISO-8601 formats, while the SimpleDateFormat approach is useful for legacy applications.

]]>
https://java2blog.com/format-instant-to-string-java/feed/ 0
Java Date to LocalDate https://java2blog.com/java-date-to-localdate/?utm_source=rss&utm_medium=rss&utm_campaign=java-date-to-localdate https://java2blog.com/java-date-to-localdate/#respond Tue, 12 Jan 2021 17:52:47 +0000 https://java2blog.com/?p=12354 In this post, we will see how to convert Date to LocalDate in java.

Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java.

Using toInstant() method of Date class

You can convert Date to LocalDate using toInstant() method of Date class. Since Instant objects are time agnostic, you need to use atZone() method to convert to derive LocalDate from it.
Here is an example:

package org.arpit.java2blog.entry;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class JavaDateToLocalDateUsingInstant {

    public static void main(String[] args) {

        Date date=new Date();
        LocalDate localDate = convertDateToLocalDateUsingInstant(date);
        System.out.println("Local Date: "+localDate);
    }

    public static LocalDate convertDateToLocalDateUsingInstant(Date date) {
        return date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }
}

Output:

Local Date: 2021-01-07

Using toInstant() method of Date class

You can convert Date to LocalDate using toInstant() method of Date class. You can use Intant.ofEpochMilli(date.getTime()) to derive instant object and use atZone() method to associate time zone to instant object.
Here is an example:

package org.arpit.java2blog.entry;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class JavaDateToLocalDateUsingOfEpochMilli {

    public static void main(String[] args) {

        Date date=new Date();
        LocalDate localDate = convertDateToLocalDateUsingOfEpochMilli(date);
        System.out.println("Local Date: "+localDate);
    }

    public static LocalDate convertDateToLocalDateUsingOfEpochMilli(Date date) {
        return Instant.ofEpochMilli(date.getTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
    }
}

Output:

Local Date: 2021-01-07

Using java.sql.Date

You can convert Date to LocalDate using java.sql.Date. In Java 8, there is new method toLocalDate() added to java.sql.Date class.`
Here is an example:

package org.arpit.java2blog.entry;

import java.time.LocalDate;
import java.util.Date;

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

        Date date=new Date();
        LocalDate localDate = convertDateToLocalDateUsingSQLDate(date);
        System.out.println("Local Date: "+localDate);
    }

    public static LocalDate convertDateToLocalDateUsingSQLDate(Date date) {
        return new java.sql.Date(date.getTime()).toLocalDate();
    }

}

Output:

Local Date: 2021-01-07

That’s all about how to convert Date to LocalDate in java

]]>
https://java2blog.com/java-date-to-localdate/feed/ 0
Java LocalDate to Date https://java2blog.com/java-localdate-to-date/?utm_source=rss&utm_medium=rss&utm_campaign=java-localdate-to-date https://java2blog.com/java-localdate-to-date/#respond Mon, 11 Jan 2021 18:22:06 +0000 https://java2blog.com/?p=11644 In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time.

There can be many ways to convert Java LocalDateTime to date.


Using Instant object

You can convert LocalDate to Date using Instant object which we can from Zone. Here is the code for the same:

Date  public static Date convertToDateUsingInstant(LocalDate date) {
        return java.util.Date.from(date.atStartOfDay()
                .atZone(ZoneId.systemDefault())
                .toInstant());
    }

Using java.sql.Date

The easiest way to convert LocalDate to Date is to use valueOf() method from java.sql.Date. You should prefer first approach because java.util.Date is meant for database layer and may change the dependency later in further java versions.

public static Date convertToDateUsingDate(LocalDate date) {
        return java.sql.Date.valueOf(date);
    }

Here is complete program to convert between LocalDate to Date.

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateToDateMain {

    public static void main(String[] args) {
        LocalDate ld = LocalDate.now();
        Date dt1=convertToDateUsingInstant(ld);
        System.out.println("Using Instant:"+dt1);
        System.out.println("=====================");
        Date dt2=convertToDateUsingDate(ld);
        System.out.println("Using java.sql.Date: "+dt2);
    }

    public static Date convertToDateUsingDate(LocalDate date) {
        return java.sql.Date.valueOf(date);
    }

    public static Date convertToDateUsingInstant(LocalDate date) {
        return java.util.Date.from(date.atStartOfDay()
                .atZone(ZoneId.systemDefault())
                .toInstant());
    }
}

Output:

Sun Thu Jan 07 00:00:00 IST 2021
=====================
2021-01-07

That’s all about Java LocalDate to Date in Java 8.

]]>
https://java2blog.com/java-localdate-to-date/feed/ 0