ListOrderedMap位于commons-collections的jar包里,与普通的map相比,ListOrderedMap的key可保持原有顺序。
package util; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.collections.map.ListOrderedMap; public class ListOrderMapTest { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "Test1"); map.put("2", "Test2"); map.put("3", "Test3"); map.put("4", "Test4"); Set<String> set1 = map.keySet(); for (String key : set1) { System.out.println(key + ":" + map.get(key)); } System.out.println("---------------------------------------"); @SuppressWarnings("unchecked") Map<String, String> listOrderedMap = ListOrderedMap.decorate(new HashMap<String, String>()); listOrderedMap.put("1", "Test1"); listOrderedMap.put("2", "Test2"); listOrderedMap.put("3", "Test3"); listOrderedMap.put("4", "Test4"); Set<String> set2 = listOrderedMap.keySet(); for (String key : set2) { System.out.println(key + ":" + listOrderedMap.get(key)); }
运行结果如下:
3:Test3
2:Test2
1:Test1
4:Test4
---------------------------------------
1:Test1
2:Test2
3:Test3
4:Test4