对List中的HashMap进行排序。

==


package znotes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class SortListHashMapByValue implements
		Comparator<HashMap<? extends Object, ? extends Comparable>> {
	private boolean flag;
	public SortListHashMapByValue(boolean flag) {
		this.flag = flag;
	}
	public SortListHashMapByValue() {
		this(true);
	}
	public int compare(HashMap<? extends Object, ? extends Comparable> o1,
			HashMap<? extends Object, ? extends Comparable> o2) {
		Comparable c1 = o1.entrySet().iterator().next().getValue();
		Comparable c2 = o2.entrySet().iterator().next().getValue();
		if (flag) {
			return c1.compareTo(c2);
		} else {
			return c2.compareTo(c1);
		}
	}

	public static void main(String[] args) {

		List<HashMap<String, Float>> list = new ArrayList<>();
		HashMap<String, Float> map = new HashMap<>();
		map.put("1", 123.0f);
		HashMap<String, Float> map1 = new HashMap<>();
		map1.put("1", 12.0f);
		HashMap<String, Float> map2 = new HashMap<>();
		map2.put("1", 1112.0f);
		list.add(map);
		list.add(map1);
		list.add(map2);
		Collections.sort(list, new SortListHashMapByValue(false));
		List<HashMap<String, Float>> list1 = list;

	}
}


==

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在JavaHashMap是一种无序的数据结构,因此不能直接对其进行排序。但是,可以通过将HashMap的键值对转换成List,然后对List进行排序来实现对HashMap排序。 具体步骤如下: 1. 将HashMap的键值对转换成List,可以使用HashMap的entrySet()方法,将其转换成Set,再使用ArrayList的构造函数将其转换成List。 2. 对List进行排序,可以使用Collections类的sort()方法,并指定排序规则。这里可以使用Comparator接口的实现类来指定排序规则,也可以直接对值或键进行排序。 3. 将排序后的List转换回HashMap,可以使用HashMap的构造函数,并传入排序后的List作为参数。 以下是示例代码: ```java HashMap<String, Integer> map = new HashMap<>(); map.put("c", 3); map.put("a", 1); map.put("d", 4); map.put("b", 2); List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getKey().compareTo(o2.getKey()); } }); HashMap<String, Integer> sortedMap = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } System.out.println(sortedMap); // 输出:{a=1, b=2, c=3, d=4} ``` 在示例代码,通过将HashMap的键值对转换成List,并使用Collections类的sort()方法对List进行排序,指定了按照键的升序排序规则。最后,将排序后的List转换回HashMap。注意,这里使用了LinkedHashMap,是因为HashMap是无序的,如果想保留排序结果,需要使用有序的Map。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值