Map maintaining insert order of key-value pairs
Many time we want to maintain order of entries as it is inserted. HashMap does not satisfy this requirement. For all such requirement java collection framework has provided LinkedHashMap.
Following example explains :
1: import java.util.*;2: class MapTest3: {4: public static void main(String[] args)5: {6: System.out.println("Using HashMap:");7: Map hashMap = new HashMap();8: hashMap.put("One","One");9: hashMap.put("Two","Two");10: hashMap.put("Three","Three");11: hashMap.put("Four","Four");12: hashMap.put("Five","Five");13: System.out.println("Complete Map content : "+ hashMap.toString());14: System.out.println("Iterating Key-Value:");15: Iterator itr = hashMap.keySet().iterator();16: while(itr.hasNext()){17: System.out.println(hashMap.get(itr.next()));18: }19:20: System.out.println("\nUsing LinkedHashMap:");21: LinkedHashMap map = new LinkedHashMap();22: map.put("One","One");23: map.put("Two","Two");24: map.put("Three","Three");25: map.put("Four","Four");26: map.put("Five","Five");27: System.out.println("Complete Map content : "+ map.toString());28: System.out.println("Iterating Key-Value:");29: itr = map.keySet().iterator();30: while(itr.hasNext()){31: System.out.println(map.get(itr.next()));32: }33: System.out.println("End of Main");34: }
Output :
---------- java ----------Using HashMap:Complete Map content : {Five=Five, Three=Three, One=One, Four=Four, Two=Two}Iterating Key-Value:FiveThreeOneFourTwoUsing LinkedHashMap:Complete Map content : {One=One, Two=Two, Three=Three, Four=Four, Five=Five}Iterating Key-Value:OneTwoThreeFourFiveEnd of MainOutput completed (0 sec consumed)
From this example, we can clearly see that LinkedHashMap maintains key-value entries as it is inserted.
Thanks! I have started using it already.
ReplyDeletewhat if we run this code again and again....what will be the o/p for HashMap???if the order is same then why???i am facing such a problem now.....help
ReplyDelete@Rahul Hashmap doesn't assure the order of insertion of key value pairs. Order of insertion and retrieval may different completely. Anyway HashMap is not suppose to maintain insertion order, it only consider the hash values of the keys.
ReplyDeleteWhat kind of map you are using and what is the problem exactly ?
i am using a Hashmap.
ReplyDeleteLater, I am using Hashmap.put <****,****> () inside a JDBCResultSet.next()
this insert is done according to the query result.
now, when i print the key and value of this Hashmap, every time the order is same, [8,1,3,2,5,4,7,6]
i was trying to get this different every time.....whatz d problem here?is it a fixed algorithm for .put method....and will it give same order always???
Thanks,
-Rahul.