map排序

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

public class Test2 {
	public static void main(String[] args) {
		List<Map.Entry<String, String>> mappingList = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("dddd", "c");
		map.put("aaaa", "b");
		map.put("bbbb", "d");
		map.put("ccccc", "a");
		

		// 通过ArrayList构造函数把map.entrySet()转换成list
		mappingList = new ArrayList<Map.Entry<String, String>>(map.entrySet());
		// 通过比较器实现比较排序
		Collections.sort(mappingList,
				new Comparator<Map.Entry<String, String>>() {
					public int compare(Map.Entry<String, String> mapping1,
							Map.Entry<String, String> mapping2) {
						// return
						// mapping1.getKey().compareTo(mapping2.getKey());
						return mapping1.getValue().compareTo(
								mapping2.getValue());
					}
				});

		for (Map.Entry<String, String> mapping : mappingList) {
			System.out.println(mapping.getKey() + ":" + mapping.getValue());
		}
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,Map是一种键值对的数据结构,其中每个键都唯一对应一个值。如果需要对Map进行排序,可以通过将Map转换为List,然后对List进行排序来实现。 例如,如果我们有一个Map<String, Integer>,希望按照值的大小对其进行排序,可以使用以下代码: ``` Map<String, Integer> map = new HashMap<>(); // 假设已经将map填充好了 List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<String, Integer> entry : list) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } ``` 在这里,我们使用了HashMap作为示例Map,并将其转换为List<Map.Entry<String, Integer>>。然后,我们使用Collections.sort()方法对List进行排序排序方式为按照值的大小升序排列。最后,我们遍历排序后的List,并打印每个键值对的内容。 需要注意的是,Java 8中的Map接口有一个新的方法entrySet().stream(),可以直接对Map进行排序,示例代码如下: ``` Map<String, Integer> map = new HashMap<>(); // 假设已经将map填充好了 map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .forEachOrdered(x -> System.out.println("Key: " + x.getKey() + ", Value: " + x.getValue())); ``` 这里,我们使用了entrySet().stream()方法将Map转换为流,然后使用sorted()方法对流进行排序排序方式为按照值的大小升序排列。最后,我们使用forEachOrdered()方法遍历排序后的流,并打印每个键值对的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linyu19872008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值