java.time
I recommend you do it using the modern Date-Time API. Depending on your requirement, you can get the list of years in the form of Integer
, String
, Year
etc.
Demo:
import java.time.LocalDate;
import java.time.Year;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> dates = List.of("2012-05-16", "2012-05-18", "2012-06-19",
"2013-01-18", "2013-01-10", "2013-08-05", "2010-07-10");
List<Integer> yearsIntList =
dates.stream()
.map(LocalDate::parse)
.map(d -> d.getYear())
.collect(Collectors.toList());
List<String> yearsStrList =
dates.stream()
.map(LocalDate::parse)
.map(d -> String.valueOf(d.getYear()))
.collect(Collectors.toList());
List<Year> yearsYearList =
dates.stream()
.map(LocalDate::parse)
.map(d -> Year.of(d.getYear()))
.collect(Collectors.toList());
System.out.println(yearsIntList);
System.out.println(yearsStrList);
System.out.println(yearsYearList);
}
}
Output:
[2012, 2012, 2012, 2013, 2013, 2013, 2010]
[2012, 2012, 2012, 2013, 2013, 2013, 2010]
[2012, 2012, 2012, 2013, 2013, 2013, 2010]
ONLINE DEMO
Note that all of your date strings are in the ISO 8601 format. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter
object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
Learn more about the modern Date-Time API* from Trail: Date Time.
Note:
Use .distinct()
before collecting the Stream
if you need a unique collection of years e.g.
List<String> yearsStrList =
dates.stream()
.map(LocalDate::parse)
.map(d -> String.valueOf(d.getYear()))
.distinct()
.collect(Collectors.toList());
Output:
[2012, 2013, 2010]
ONLINE DEMO
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.