0

I have a Map<String, Id> and i want to sort them based on ENUM with sort order..

Map values: Apple, 1
            Banana, 2
            Grapes, 3
            Coconut, 4
            Mango, 5
            Avocado, 6

my ENUM compose of

FruitName(sortOrder, id)

What is the best way to do the sorting?

  • So use a `TreeMap` with a `Comparator`, assuming the `String` key is a fruit name. --- Or are you asking about sorting by value? If so: [Sort a Map by values](https://stackoverflow.com/q/109383/5221149) – Andreas Apr 16 '20 at 06:37
  • but how can i apply the enum? and there are scenario that Mango is not in the enum order.. so it will just put to last.. – jodevelofer Apr 16 '20 at 06:41
  • You didn't say that new rule in the question. Please **edit** the question and add relevant information. --- Are you asking how to find enum constant `FruitName.Banana` from the string value `"Banana"`? If so, call `FruitName.valueOf("Banana")` – Andreas Apr 16 '20 at 06:42
  • no we will find it by ID. – jodevelofer Apr 16 '20 at 06:48
  • So sort map by value. Then see the link I gave. – Andreas Apr 16 '20 at 06:49
  • Use your enum objects as the key to your map rather than strings. Use `EnumMap` Implementation of `Map`. That implementation maintains an iteration order based on the order in which the enum objects were named in the enum. `Map< Fruit , Id > = new EnumMap<>() ;` – Basil Bourque Apr 16 '20 at 07:16
  • the design is already there.. they uses String.. – jodevelofer Apr 16 '20 at 07:24

0 Answers0