6

I have HashMAp

 items = new HashMap<String, String>();
        items.put("A", "1");
        items.put("B", "2");
        items.put("C", "3");

I need for each last to first.

"C", "3"
"B", "2"
"A", "1"
2
  • The terms Last and First seem to denote time. Most of the answers I see assume Last and First are semantic (e.g. C is larger than A and thus Last). OrderedMaps won't help you if you need insertion time ordering and don't have the insertion timestamp in the key. Commented Nov 21, 2010 at 10:11
  • 1
    HashMap doesn't guarantee any order for its elements. In particular, it doesn't guarantee that the order remains constant over time. Thus, HashMap is not what you want if you have to maintain any kind of order. Commented Nov 21, 2010 at 10:46

4 Answers 4

6

You can use a NavigableMap (TreeMap is a NavigableMap), which is a SortedMap with navigation capabilities.

NavigableMap#descendingMap() returns a reverse order view (not a copy) of the mappings contained in this map.

Example :

NavigableMap<String, String> items = new TreeMap<String, String>();
items.put("B", "2");
items.put("A", "1");
items.put("C", "3");

for (Map.Entry<String, String> e : items.entrySet()) {
    System.out.println(e);
}
// gives
// A=1
// B=2
// C=3

for (Map.Entry<String, String> e : items.descendingMap().entrySet()) {
    System.out.println(e);
}

// gives
// C=3
// B=2
// A=1

Note : This answer is valid if you care about the natural ordering of the keys in your Map. If you care about the insertion ordering or the access ordering, then have a look at LinkedHashMap.

Note 2 : In your question, you used a HashMap. Please note that HashMap doesn't guarantee any order for its elements. Actually, it doesn't even guarantee the order will remain constant over time. See the first paragraph of HashMap's javadoc for further references.

Sign up to request clarification or add additional context in comments.

2 Comments

The order is based on key semantics. But I think the question is about insertion time. So a reverse order won't help you as the order criterium (insertion time) is not part of the key.
I added a note to clarify things
4

EDIT: Myself and Matthew clearly have different interpretations of what your question means. Do you mean reverse order that you inserted, or reverse order of keys?

If you mean reverse order of keys, here's how to do it:

Use an ordered Map, like TreeMap and then iterate over items.keySet().

TreeMap sorts by natural order of your key values, so you will need to pass in a comparator to the constructor to sort the keys in reverse order:

Map<String, String> items = new TreeMap<String, String>(new Comparator<String>() {
  public int compare(String a, String b) {
    return b.compareTo(a);
  }
});

items.put("A", "1");
items.put("B", "2");
items.put("C", "3");

for (String s: items.keySet()) {
  System.out.println(s + " " + items.get(s));
}

1 Comment

This code is equivalent : Map<String, String> items = new TreeMap<String, String>(Collections.reverseOrder());
1

HashMap doesn't guarantee any ordering. If you use LinkedHashMap, it will be ordered by insertion, but there is still no convenient way to go backwards.

One way would be to call items.entrySet(). That returns a Set<Map.Entry>. You can then get the size of the set, call toArray(), then do a descending for loop.

Comments

0

Another method - create a SortedSet of your keys:

import java.util.*;

class MyComparator implements Comparator<String> {
    public int compare(String a, String b) {
        return -a.compareTo(b);
    }

    public boolean equals(String a, String b) {
        return a.equals(b);
    }
}

public class test {
    public static void main(String[] args) {
        HashMap<String, String> items = new HashMap<String, String>();
        items.put("A", "1");
        items.put("B", "2");
        items.put("C", "3");

        TreeSet<String> ts = new TreeSet<String>(new MyComparator());
        ts.addAll(items.keySet());
        for(Iterator<String> i = ts.iterator(); i.hasNext(); ) {
            String key = i.next();
            System.out.println("key: " + key + ", value: " + items.get(key));
        }
    }
}

output:

key: C, value: 3
key: B, value: 2
key: A, value: 1

2 Comments

You assume Last is in the context of the key, but I think he meant insertion time. If the insertion time is not in the key a comparator cannot help you.
I disagree. I don't think insertion time has anything to do with it. I think he made the mistake of thinking a HashMap could be iterated in some order, and wants it reversed. I'm assuming the order he meant was alphabetical.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.