0

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?

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Srishti
  • 355
  • 1
  • 17

1 Answers1

1

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.

Abdul Wadood
  • 1,161
  • 1
  • 10
  • 18