Srishti
Srishti

Reputation: 355

How to sort map of object on the basis of date

How to sort map on the basis of time field in object. My Map looks like:

Map<Integer, ShiftDTO> -> ShiftDTO consist of following key: shiftName, shiftStartTime, shiftEndTime. shiftStartTime is of type Date, and I want to sort on the basis of date in ascending order. Following code I was using to sort on the basis of map key:

LinkedHashMap<Integer, ShiftDTO> sortedMap = new LinkedHashMap<Integer, ShiftDTO>();
    v.getShiftHashMap().entrySet().stream().sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

But how can I sort all shift entries on the basis of shiftStartTime?

Upvotes: 0

Views: 200

Answers (1)

Abdul Wadood
Abdul Wadood

Reputation: 1171

You just need to change the comparator in the sorted method. You can use the following comparator:

(entry1, entry2) -> entry1.getValue().shiftStartTime.compareTo(entry2.getValue().shiftStartTime)

Or else you can use a TreeMap and pass this comparator to its constructor while creating the map.

Upvotes: 1

Related Questions