I have a list which I convert to a map to do some work. After that, i convert the map back again to a list, but this time the order is random. I need the same initial order retained in my second list.
the obvious reason is that a HashMap doesn't maintain order. But I need to do something so that it does. I cannot change the Map implementation.How can I do that ?
Consider the given code:
import java.util.*;
public class Dummy {
public static void main(String[] args) {
System.out.println("Hello world !");
List<String> list = new ArrayList<String>();
list.add("A");list.add("B");list.add("C");
list.add("D");list.add("E");list.add("F");
Map<String,String> map = new HashMap<String, String>();
for(int i=0;i<list.size();i=i+2)
map.put(list.get(i),list.get(i+1));
// Use map here to do some work
List<String> l= new ArrayList<String>();
for (Map.Entry e : map.entrySet()) {
l.add((String) e.getKey());
l.add((String) e.getValue());
}
}
}
For ex - Initially, when I printed the list elements, it printed out
A B C D E F
Now, when I print the elements of List l
, it printed out
E F A B C D