按 Java 中的键对 HashMap 进行排序
首先,创建一个 HashMap −
HashMap hm = new HashMap();
向 HashMap 中添加一些元素 −
hm.put("Shirts", new Integer(700)); hm.put("Trousers", new Integer(600)); hm.put("Jeans", new Integer(1200)); hm.put("Android TV", new Integer(450)); hm.put("Air Purifiers", new Integer(300)); hm.put("Food Processors", new Integer(950));
现在,使用 TreeMap 对 HashMap 按键进行排序 −
Map<String, String> sort = new TreeMap<String, String>(hm); System.out.println("Sorted Map based on key = "+sort);
按键对 HasMap 进行排序的示例如下 −
示例
import java.util.*; public class Demo { public static void main(String args[]) { HashMap hm = new HashMap(); hm.put("Shirts", new Integer(700)); hm.put("Trousers", new Integer(600)); hm.put("Jeans", new Integer(1200)); hm.put("Android TV", new Integer(450)); hm.put("Air Purifiers", new Integer(300)); hm.put("Food Processors", new Integer(950)); System.out.println("Map = "+hm); Map<String, String> sort = new TreeMap<String, String>(hm); System.out.println("Sorted Map based on key = "+sort); } }
输出
Map = {Shirts=700, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600} Sorted Map based on key = {Air Purifiers=300, Android TV=450, Food Processors=950, Jeans=1200, Shirts=700, Trousers=600}
广告