0

So I have this method here:

public Map<Long,Pkmn> sortByCreator(Map<Long,Pkmn> pkmns) {

        Collection<Pkmn> pkmn_to_get = pkmns.values();
        pkmns = null; //Delete useless memory.

        List<Pkmn> pkmn_to_sort = new LinkedList<Pkmn>();

        for(Pkmn pkmn : pkmn_to_get) {
            pkmn_to_sort.add(pkmn);
        }

        Collections.sort(pkmn_to_sort);

        Map<Long,Pkmn> return_map = new HashMap<Long,Pkmn>();

        for(Pkmn pkmn_data : pkmn_to_sort) {
            return_dex.put(pkmn_data.getId(), pkmn_data);
        }

        return return_dex;
    }

The problem is after Collections.sort(pkmn_to_sort) sorts the array; the for loop below adds they pkmn_data to the Map, but its un_sorted.

I know Map isn't like a stack where it goes in one after the other; but I want it to in this case.

Does anyone have a way of adding List items to a Map in the order of the List?

Thanks in advance :)

Mike_1234
  • 13
  • 5
  • 1
    Note that this is not useful for anything at all: `pkmns = null; //Delete useless memory.` – Jesper Jun 04 '20 at 16:23

1 Answers1

1

HashMap is inherently unordered, try a LinkedHashMap to preserve the iteration order of the map relative to insertion.

Rogue
  • 11,105
  • 5
  • 45
  • 71