Start New Discussion within our Software Development Community

I need to append to Map to another Map... and this is what i did ..

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class sampl {
 
	public static void main(String[] args) {
		 Map<String,String> FileMap =new HashMap<String, String>();
		 Map<String,String> stateMap =new HashMap<String, String>();
		 
		 stateMap.put("1", "value0");
		 stateMap.put("12", "value1");
		 stateMap.put("13", "value2");
		 stateMap.put("14", "value3");
 
		 FileMap.put("value changed", "key value");
		 FileMap.putAll(stateMap);
	
	            Iterator it = FileMap.entrySet().iterator();
	            while (it.hasNext()) {
	                Map.Entry pairs = (Map.Entry)it.next();
	                System.out.println(pairs.getKey() + " = " + pairs.getValue());
	            }	            
	        }	
	}

The Out put appears as follows

1 = value0
value changed = key value
13 = value2
14 = value3
12 = value1

What i expected here is to print the out put as follows >>

value changed = key value << So this appears first
1 = value0
13 = value2
14 = value3
12 = value1


according to the code.. i am adding FileMap.put("value changed", "key value"); First and FileMap.putAll(stateMap); thereafter. So why has the order changed in the above output.

how can i edit this code to display the output as follows >>>>

value changed = key value << This should appear first , then the map that i added
1 = value0
13 = value2
14 = value3
12 = value1

note:: First of all i need to display value changed = key value , and the display the remaining of the map..

I need to display values in the order of insertion
Help !!!!

A HashMap is unable to do that for you. You could look at TreeMap which is a sorted map which will let you write your own comparator while inserting key values.

Cheers

This article has been dead for over six months. Start a new discussion instead.