0

I would like to change the elements in my LinkedHashMap in the reverse order. Something like this:

public static void main(String[] args){
    Map<String, Integer> map = new LinkedHashMap<>();
    map.put("Hello", 2);
    map.put("World", 1);
    reverse(map);
    System.out.println(map);// {Wordl=1, Hello=2}
}

public static void reverse(Map<String, Integer> map){
   // Reverse my map...
}

But I did not find anything that could help me to do this. Can someone suggest how this can be solved? Thank.

Stan
  • 3
  • 2

3 Answers3

1

You can use this code to iterate in reverse order:

   ListIterator<Map.Entry<String, Integer>> iterator = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()).listIterator(map.size());
            while (iterator.hasPrevious()) {
                Map.Entry<String, Integer> entry = iterator.previous();
                System.out.println(entry.getValue());
            }
Ehsan Mashhadi
  • 2,568
  • 1
  • 19
  • 30
0

Have you looked here:

How to traverse Linked Hash Map in reverse?

Check out the second answer which offers options on how to traverse. Also see the link to the Guava library.

Happy
  • 59
  • 6
0

// You can do take use of Arraylist. Here's an implementation.

    public static void main(String[] args) {

    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("Hello", "2");
    map.put("World", "1");
    // create an arraylist initialized with keys of map
    ArrayList keyList = new ArrayList(map.keySet());
    for (int i = keyList.size() - 1; i >= 0; i--) {
        // get key
        String key = (String) keyList.get(i);
        System.out.println("Key :: " + key);
        // get value corresponding to key
        String value = map.get(key);
        System.out.println("Value :: " + value);
        System.out.println("--------------------------------");
    }
}
Jabongg
  • 2,099
  • 2
  • 15
  • 32