map自定义排序,根据键或者值排队
  TEZNKK3IfmPf 2023年11月15日 12 0

核心比较器
比较器之根据键排序

package cn.com.hongyitech.accountsystem.utils;

import java.util.Comparator;

class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String key1, String key2) {
        
        return key1.compareTo(key2);
    }
}

比较器之根据值排序

package cn.com.hongyitech.accountsystem.utils;

import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;

class MapValueComparator implements Comparator<Map.Entry<String, String>> {

  @Override
  public int compare(Entry<String, String> map1, Entry<String, String> map2) {

    return map1.getValue().compareTo(map2.getValue());
  }
}

根据键排序

/**
   * 使用 Map按key进行排序
   * 
   * @param map
   * @return
   */
  public static Map<String, String> sortMapByKey(Map<String, String> map) {
    if (map == null || map.isEmpty()) {
      return null;
    }

    Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());

    sortMap.putAll(map);

    return sortMap;
  }

根据值排序

/**
   * 使用 Map按value进行排序
   * 
   * @param map
   * @return
   */
  public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
    if (oriMap == null || oriMap.isEmpty()) {
      return null;
    }
    Map<String, String> sortedMap = new LinkedHashMap<String, String>();
    List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
    Collections.sort(entryList, new MapValueComparator());

    Iterator<Map.Entry<String, String>> iter = entryList.iterator();
    Map.Entry<String, String> tmpEntry = null;
    while (iter.hasNext()) {
      tmpEntry = iter.next();
      sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
    }
    return sortedMap;
  }

测试用例

public static void main(String[] args) {

    Map<String, String> map = new TreeMap<String, String>();

    map.put("2018-12-06", "1");
    map.put("2018-12-03", "2");
    map.put("2018-12-07", "4");
    map.put("2018-12-04", "2");
    map.put("2018-12-01", "3");

    Map<String, String> resultMapByKey = sortMapByKey(map); // 按Key进行排序
    Map<String, String> resultMapByValue = sortMapByValue(map); // 按Value进行排序

    for (Map.Entry<String, String> entry : resultMapByKey.entrySet()) {
      System.out.println(entry.getKey() + " " + entry.getValue());
    }
    System.out.println("******上面根据key*********************下面根据value********");
    for (Map.Entry<String, String> entry : resultMapByValue.entrySet()) {
      System.out.println(entry.getKey() + " " + entry.getValue());
    }
  }

结果

2018-12-01 3
2018-12-03 2
2018-12-04 2
2018-12-06 1
2018-12-07 4
******上面根据key*********************下面根据value********
2018-12-06 1
2018-12-03 2
2018-12-04 2
2018-12-01 3
2018-12-07 4


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
TEZNKK3IfmPf