假设以下是带有未排序键的Map-
HashMap<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("6", "B"); map.put("3", "C"); map.put("7", "D"); map.put("5", "E"); map.put("2", "F"); map.put("4", "G"); map.put("8", "H");
现在,对上面的映射进行排序。以下tMap的结果将是按键排序的映射-
Map<String, String>tMap = 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[] args) { HashMap<String, String>map = new HashMap<String, String>(); map.put("1", "A"); map.put("6", "B"); map.put("3", "C"); map.put("7", "D"); map.put("5", "E"); map.put("2", "F"); map.put("4", "G"); map.put("8", "H"); Map<String, String>tMap = new TreeMap<String, String>(map); System.out.println("Sorted Map values: "+tMap); } }
输出结果
{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H}