Search code examples
javaandroidlistdatejava-time

Find all the years in a list of dates


So, I have a list of dates that is something like this:

List<String> dates = ["2012-05-16", "2012-05-18", "2012-06-19", "2013-01-18", "2013-01-10", "2013-08-05", "2010-07-10"...]

The list goes on with like 100 dates and I want to retrieve all the years that exists on the list. (to get a result like this)

List<String> years = ["2012", "2013", "2010"...]

Solution

  • Use a substring to split the first 4 characters of each item out. It will leave you with the year

       for (String s : dates) {
             String year = s.subString(0,5);
             years.add(year);
    
          }
    

    or you could use the .split() method

    String year =  s.split("-")[0];
    

    EDIT

    Upon further clarification, the question was to get unique years in the array list.

    This can be done by passing the arraylist into a Set which does not accept duplicate values and then passing the set back into the array

    // add elements to al, including duplicates
    Set<String> hs = new HashSet<>();
    hs.addAll(years);
    years.clear();
    years.addAll(hs);
    

    From How do I remove repeated elements from ArrayList?