HashMap根据value排序

将HashMap通过value或value对象中的某个变量、对象进行排序,首先要将value取出保存在list里面,这里以value为student对象为例

//方法一:直接获取values集合
	public static void sortByScore(Map<Integer, Student> m1) {
		//获取map的value集合
		Collection<Student> c1 = m1.values();
		//将value集合存入list
		List<Student> l1 = new ArrayList<Student>(c1);	
		/*
		 如果需要对每个数据做处理,可以使用迭代器遍历添加
		List<Student> l1 = new ArrayList<Student>();
		Iterator<Student> iter = c1.iterator();
		Student s1 = new Student();
		while(iter.hasNext()) {
			s1 = iter.next();
			s1.setId(11);
			l1.add(s1);
		}
		*/
		Collections.sort(l1,new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				//这里通过sroce排序
				return o1.getSroce().compareTo(o2.getSroce());
				//相当于return o1.getSroce()-o2.getSroce();
			}
		});
	}
//方法二:获取map的entry集合
	public static void sort(Map<Integer, Student> m1) {
		//获取map的entrySet集合
		Set<Entry<Integer, Student>> es = m1.entrySet();
		//将entry集合存入list
		List<Entry<Integer, Student>> l1 = new ArrayList<>(es);
		Collections.sort(l1, new Comparator<Entry<Integer, Student>>() {

			@Override
			public int compare(Entry<Integer, Student> o1, Entry<Integer, Student> o2) {
				//通过获取entry的value(Student对象),再获取分数进行比较
				return o1.getValue().getSroce().compareTo(o2.getValue().getSroce());
			}

		});
	}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值