How to iterate Map in reverse order

Iterating in reverse order means fetching last element of the map first, second last element at second position and so on. Simple logic is to start a loop from last position of the map till its beginning and fetch element at that position but unfortunatelyjava.util.Map interface or any of its implementations does not have a method to retrieve elements based on index hence you cannot fetch an element based on its position. So how can we reverse iterate a map. Read on !!!

Method 1 : Using java.util.ArrayList initialized to Keys of Map

Initialize a java.util.LinkedHashMapand add some entries to it. Create a java.util.ArrayListwith the keys of this map using keySet()method of map. Now this newly created list contains all the keys of the map in the order in which they were inserted into the map. Since java.util.ArrayListprovides a get()method to fetch an element using its index, we can iterate over this list in reverse order. Each iteration gives us the key and using this key, we easily get the value corresponding to the key from the map.

static void methodOne() {
	Map<String, String> map = new LinkedHashMap<String, String>();
	map.put("Key1", "Value1");
	map.put("Key2", "Value2");
	map.put("Key3", "Value3");
	map.put("Key4", "Value4");
	map.put("Key5", "Value5");
	map.put("Key6", "Value6");
	//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 = 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("--------------------------------");
	}
}

Output :

Key :: Key6
Value :: Value6
——————————–
Key :: Key5
Value :: Value5
——————————–
Key :: Key4
Value :: Value4
——————————–
Key :: Key3
Value :: Value3
——————————–
Key :: Key2
Value :: Value2
——————————–
Key :: Key1
Value :: Value1
——————————–

Method 2 : Using array initialized to Keys of Map

Initialize a java.util.LinkedHashMapand add some entries to it. Get a java.util.Setinitialized with the the keys of this map using keySet()method of map. Now this newly created set contains all the keys of the map in the order in which they were inserted into the map. Convert this set to an array using toArray()method of the set. Now iterate over this array in reverse order using traditional index based for loop. Each iteration gives us the key and using this key, we easily get the value corresponding to the key from the map.

static void methodTwo() {
	Map<String, String> map = new LinkedHashMap<String, String>();
	map.put("Key1", "Value1");
	map.put("Key2", "Value2");
	map.put("Key3", "Value3");
	map.put("Key4", "Value4");
	map.put("Key5", "Value5");
	map.put("Key6", "Value6");
	//get keyset of map
	Set keySet = map.keySet();
	//convert it to an array
	Object[] keyArray = keySet.toArray();
	//set up a loop to iterate the array of keys backwards
	for (int i = keyArray.length - 1; i >= 0; i--) {
		//get key
		String key = (String)keyArray[i];
		System.out.println("Key :: " + key);
		//get value corresponding to key
		String value = map.get(key);
		System.out.println("Value :: " + value);
		System.out.println("--------------------------------");
	}
}

Output :

Key :: Key6
Value :: Value6
——————————–
Key :: Key5
Value :: Value5
——————————–
Key :: Key4
Value :: Value4
——————————–
Key :: Key3
Value :: Value3
——————————–
Key :: Key2
Value :: Value2
——————————–
Key :: Key1
Value :: Value1
——————————–

Let’s tweak in :

  1. If the order of insertion is to be maintained in any form, be it forward or reverse, then use 'java.util.LinkedHashMapas it maintains the order of insertion of elements.
  2. If java.util.HashMapis used in above examples then order of elements can not be guaranteed.
  3. Method 1 uses a single argument constructor of java.util.ArrayListwhich takes a java.util.Collection. Newly created list will be populated with the contents of this collection. keySet() method of Set returns a java.util.Set which extends java.util.Collection and hence can be passed to the constructor of java.util.ArrayList.
  4. The type of the array returned by toArray()method of java.util.Setis java.lang.Object. This is because java.util.Setis generic and its type is not known unless it is initialized.

 

0

This Post Has 2 Comments

  1. Very Informative and helpful

    1. Thanks Amandeep…Keep visiting!!!

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.