Search code examples
javaandroidindexinghashmap

Add new Key to last index of HashMap instead of first index


I have a HashMap and I am iterating over a List to populate this HashMap:

List<ParseObject> objects // this has already objects;

final HashMap<String, ArrayList<ParseObject>> categoryTopics = new HashMap<>();
for (final ParseObject object : objects) {

    final String category = object.getParseObject("helpCategory").fetchIfNeeded().getString("name");
    if (categoryTopics.containsKey(category)) {
        final ArrayList<ParseObject> topics = categoryTopics.get(category);
        topics.add(object);
        categoryTopics.put(category, topics);
    } else {
        final ArrayList<ParseObject> topics = new ArrayList<>();
        topics.add(object);
        categoryTopics.put(category, topics);
    }
}

It seems and works simple: I iterate over a List of objects and try to get a String. If this String/Key is present in the HashMap, I update the value, if not, I create a new entry in the HashMap.

The List contains 6 objects. The first 3 have the String/Key: "Health", and the other 3 have the String/Key: "Visa".

When I iterate the first 3 objects ("Health"), the HashMap has a key "Heatlh" in index 0 (first key) with 3 objects, but when I go for the 4th object which has a different Key ("Visa"), this new Key goes to the index 0 (first key) and the previous Key goes to index 1 (second key). It shouldn't be the other way around?

The second Key ("Visa") should go to index 1 instead of replacing the first Key at index 0 right? Am I iterating and populating the HashMap the wrong way or is this the correct way the HashMap Class work?


Solution

  • HashMap has no ordering. If you want the keys to be ordered according to insertion order, use a LinkedHashMap. If you want them to be ordered according to some other ordering, use a TreeMap with the appropriate Comparator<String> to define the ordering.

    List<ParseObject> objects // this has already objects;
    
    final Map<String, ArrayList<ParseObject>> categoryTopics = new LinkedHashMap<>();
    for (final ParseObject object : objects) {
    
        final String category = object.getParseObject("helpCategory").fetchIfNeeded().getString("name");
        if (categoryTopics.containsKey(category)) {
            final ArrayList<ParseObject> topics = categoryTopics.get(category);
            topics.add(object);
            categoryTopics.put(category, topics);
        } else {
            final ArrayList<ParseObject> topics = new ArrayList<>();
            topics.add(object);
            categoryTopics.put(category, topics);
        }
    }