Ingram
Ingram

Reputation: 674

sorting a LinkedHashset by date time

I have the following LinkedHashset

It is as LinkedHashset because i have many duplicate entries upon addition and it prevents this.

How can i then sort my LinkedHashset

LinkedHashSet<String> uniqueStrings = new LinkedHashSet<>();

uniqueStrings.add("03/03/2016  00:00:00");
uniqueStrings.add("03/03/2016  00:30:00");
uniqueStrings.add("03/03/2016  01:00:00");
uniqueStrings.add("03/03/2016  00:30:00");
uniqueStrings.add("03/03/2016  00:01:00");



List<String> asList = new ArrayList<>(uniqueStrings);
System.out.println((asList+ "\n"));

Upvotes: 1

Views: 911

Answers (1)

andrucz
andrucz

Reputation: 2021

Use a TreeSet with a comparator that parses text to Date.

private static Date safeParse(DateFormat dateFormat, String str) {
    try {
        return dateFormat.parse(str);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
}

public static void main(String[] args) {
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Comparator<String> comparator = (a, b) -> safeParse(format, a).compareTo(safeParse(format, b));

    Set<String> uniqueStrings = new TreeSet<>(comparator);

    uniqueStrings.add("03/03/2016  00:00:00");
    uniqueStrings.add("03/03/2016  00:30:00");
    uniqueStrings.add("03/03/2016  01:00:00");
    uniqueStrings.add("03/03/2016  00:30:00");
    uniqueStrings.add("03/03/2016  00:01:00");

    uniqueStrings.stream().forEach(System.out::println);
}

Upvotes: 2

Related Questions