java 对hashmap排序_根据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 sort = new TreeMap(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 sort = new TreeMap(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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值