根据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}热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志