Search code examples
javaarraylist

Sort array list based on most recent date in mm/dd/yy format in Java


I'm trying to sort an array based on sold date which in the format of MM/dd/yy. Currently, I'm getting wrong date in the first object of the array after sorting. The expected date in the first object in the sorted array is 01/12/24.

Code

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

class Car{
    String name;
    String sold;
    public Car(String name, String sold){
        this.name = name;
        this.sold = sold;
    }
    public String getSold(){
        return this.sold;
    }
}

public class MyClass {
    public static void main(String args[]) {
    
      List<Car> list = new ArrayList<Car>();
      list.add(new Car("bmw", "01/12/24"));
      list.add(new Car("jeep", "02/12/23"));
      list.add(new Car("audi", "12/12/23"));
      
      List<Car> sortedList = list.stream().sorted(Comparator.comparing(Car::getSold).reversed()).collect(Collectors.toList());
      
      System.out.println("sorted "+ sortedList.get(0).sold);
    }
}

I created a working example using JDoodle. Could anyone please help?


Solution

  • You have to parse sold date as a date and compare by it:

        DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("MM/dd/yy");
        List<Car> sortedList = list.stream()
                .sorted(Comparator.<Car, LocalDate>comparing(car -> LocalDate.parse(car.getSold(), dayFormatter)).reversed())
                .toList();