java map key 比较_JAVA map按照key,value比较

import java.util.*;

public class MapSortDemo {

public static void main(String[] args) {

Map map = new HashMap<>();

map.put("1", "4");

map.put("3", "3");

map.put("2", "2");

map.put("4", "1");

//Map resultMap = sortMapByKey(map);    //按Key进行排序:1.treemap的性质

Map resultMap = sortMapByKey2(map); //按key进行排序:2.list,自定义比较器(排序后需要LinkedHashMap保存)

// Map resultMap = sortMapByValue(map); //按Value进行排序:list,自定义比较器

for (Map.Entry entry : resultMap.entrySet()) {

System.out.println(entry.getKey() + " " + entry.getValue());

}

}

/**

* 使用 TreeMap的性质按key进行排序

* @param map

* @return

*/

public static Map sortMapByKey(Map map) {

if (map == null || map.isEmpty()) {

return null;

}

//TreeMap默认用key的自然排序,所以不用声明比较器也可以实现key排序,比较器可以自定义排序规则,比如倒序

//Map sortMap = new TreeMap();

//TreeMap构造方法可以有比较器参数~但是比较器只能是对key进行比较

Map sortMap = new TreeMap(new MapKeyComparator());

sortMap.putAll(map);

return sortMap;

}

/**

* 使用 list按key进行排序

* @param map

* @return

*/

public static Map sortMapByKey2(Map map) {

if (map == null || map.isEmpty()) {

return null;

}

List> list = new ArrayList<>(map.entrySet());

Collections.sort(list,new MapKeyComparator2());

Map sortMap = new LinkedHashMap<>();

Iterator> iterable = list.iterator();

while (iterable.hasNext()){

Map.Entry tmpEntry = iterable.next();

sortMap.put(tmpEntry.getKey(),tmpEntry.getValue());

}

return sortMap;

}

/**

* 使用 List对Map按value进行排序

* @param oriMap

* @return

*/

public static Map sortMapByValue(Map oriMap) {

if (oriMap == null || oriMap.isEmpty()) {

return null;

}

//一定是LinkedHashMap,因为LinkedHashMap保证put顺序和输出顺序一致!

Map sortedMap = new LinkedHashMap<>();

//map.entry把map的当节点装进list,对list排序

List> entryList = new ArrayList<>(oriMap.entrySet());

Collections.sort(entryList, new MapValueComparator());

Iterator> iter = entryList.iterator();

Map.Entry tmpEntry = null;

while (iter.hasNext()) {

tmpEntry = iter.next();

sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());

}

return sortedMap;

}

}

class MapKeyComparator implements Comparator {

@Override

public int compare(String str1, String str2) {

return str2.compareTo(str1);

}

}

class MapValueComparator implements Comparator> {

@Override

public int compare(Map.Entry me1, Map.Entry me2) {

return me1.getValue().compareTo(me2.getValue());

}

}

class MapKeyComparator2 implements Comparator> {

@Override

public int compare(Map.Entry me1, Map.Entry me2) {

return me1.getKey().compareTo(me2.getKey());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值