quma
quma

Reputation: 5733

Java-8 - sort keys of Map

I have this Java Map:

 Map<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject>
 ....
 public enum ScheduleAbsenceHeaderHistoryTypeEnum {

     ADDITIONAL_HOURS("ADDITIONAL_HOURS"),
     HOLIDAY("HOLIDAY"),
     REMAINING_HOLIDAY_HOURS("REMAINING_HOLIDAY_HOURS"),
     REMAINING_HOLIDAY_DAYS("REMAINING_HOLIDAY_DAYS"),
     TRANSFER_HOLIDAY("TRANSFER_HOLIDAY"),
     INCREMENT_HOLIDAY("INCREMENT_HOLIDAY"),
     ..

and I will sort the keys of the map alphabetically. Is there a possibility to do this in a simple way?

Upvotes: 1

Views: 60

Answers (2)

Holger
Holger

Reputation: 298153

You can create a map sorted by the enum’s name like

Map<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject> map
    = new TreeMap<>(Comparator.comparing(Enum::name));

This uses the constant name as declared in the enum class, e.g.

enum ScheduleAbsenceHeaderHistoryTypeEnum {
    ADDITIONAL_HOURS, HOLIDAY, REMAINING_HOLIDAY_HOURS,
    REMAINING_HOLIDAY_DAYS, TRANSFER_HOLIDAY, INCREMENT_HOLIDAY,
}

There is no need to specify that name manually.

But if you have a property that might be different from the name, you may use

Map<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject> map
  =new TreeMap<>(Comparator.comparing(ScheduleAbsenceHeaderHistoryTypeEnum::getProperty));

to sort by that specific property.

Upvotes: 2

Harmlezz
Harmlezz

Reputation: 8068

Given Map<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject> map:

    map.keySet().stream()
            .sorted(Comparator.comparing(ScheduleAbsenceHeaderHistoryTypeEnum::getName))
            .collect(Collectors.toList());

will produce a sorted List<ScheduleAbsenceHeaderHistoryTypeEnum>.

Edit:

If you like to get a Map which has its keys sorted while you put elements into it use something like this:

SortedMap<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject> map =
    new TreeMap<ScheduleAbsenceHeaderHistoryTypeEnum, ValueObject>(comparing(ScheduleAbsenceHeaderHistoryTypeEnum::getName)) {{
        put(HOLIDAY, null);
        put(REMAINING_HOLIDAY_DAYS, null);
        put(TRANSFER_HOLIDAY, null);
        put(INCREMENT_HOLIDAY, null);
        put(ADDITIONAL_HOURS, null);
    }};

The statement:

map.keySet().forEach(System.out::println);

will produce the following output:

ADDITIONAL_HOURS
HOLIDAY
INCREMENT_HOLIDAY
REMAINING_HOLIDAY_DAYS
TRANSFER_HOLIDAY

Upvotes: 1

Related Questions