Find Maximum Date From ArrayList In Java - Java @ Desk

Saturday, November 1, 2014

Find Maximum Date From ArrayList In Java






Find Maximum Date From ArrayList In Java

There are two ways to get maximum Date from an ArrayList:

1) Collections.max() from java.util.Collections
3) Using Collections.sort() from java.util.Collections

Sample Implementation:

package com.learning;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class FindMaxDateArrayList {

 public static void main(String args[]) throws ParseException {
  List<Date> dates = new ArrayList<Date>();

  SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
  Date date = fmt.parse("2013-07-06");
  Date dateOne = fmt.parse("2017-05-06");
  Date dateTwo = fmt.parse("2001-01-06");

  dates.add(date);
  dates.add(dateOne);
  dates.add(dateTwo);

  // Using java.util.Collections
  System.out.println("Maximum Element : " + fmt.format(Collections.max(dates)));

  // // Using Sort Technique of java.util.Collections
  Collections.sort(dates);
  System.out.println("Maximum Element After Sorting - " + fmt.format(dates.get(dates.size() - 1)));

 }
}






No comments:

Post a Comment