要将HashMap转换为TreeMap,让我们首先创建一个具有键值对的Map-
Map<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G");
现在,将上面的HashMap转换为TreeMap-
Map<String, String>sorted = new TreeMap<String, String>(map);
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Demo { public static void main(String[] a) { Map<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); map.put("4", "D"); map.put("5", "E"); map.put("6", "F"); map.put("7", "G"); map.put("8", "H"); map.put("9", "I"); Map<String, String>sorted = new TreeMap<String, String>(map); System.out.println("Sorted Map = "+sorted); } }
输出结果
Sorted Map = {1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I}