Find Maximum LocalDateTime From ArrayList In Java 8 - Java @ Desk

Thursday, March 29, 2018

Find Maximum LocalDateTime From ArrayList In Java 8

Maximum date can be fetched from the List using the Collections interface.

Collections interface provide the methods to find the maximum value out of a collection of dates.

In this case we will pass ArrayList of LocalDateTime object that contains the dates.

Below is a sample implementation that retrieves the maximum date from a ArrayList -

package com.learning;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FindMaxLocalDateTimeArrayList {

 public static void main(String args[]) throws ParseException {

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  LocalDate ld = LocalDate.parse("2018-03-22T18:02:32.000Z", formatter);
  LocalDateTime ldt = LocalDateTime.of(ld, LocalDateTime.now().toLocalTime());

  List<LocalDateTime> localDateTimes = new ArrayList<>();
  localDateTimes.add(ldt);
  localDateTimes.add(LocalDateTime.of(LocalDate.parse("2018-03-25T18:02:32.000Z", formatter),
    LocalDateTime.now().toLocalTime()));
  localDateTimes.add(LocalDateTime.of(LocalDate.parse("2018-03-16T18:02:32.000Z", formatter),
    LocalDateTime.now().toLocalTime()));

  System.out.println(Collections.max(localDateTimes));
 }
}






No comments:

Post a Comment