• Map的内容按字母顺序排序


    map有自带的排序功能,但需要重写排序方法,代码如下:

    package coreJava.com.shindo.corejava.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;
    import java.util.Map.Entry;
    
    public class MapSort {
        /**
         * 
         * @Title: sortMap
         * @Description: 对集合内的数据按key的字母顺序做排序
         */
        public List<Map.Entry<String, String>> sortMap(final Map<String, String> map) {
            final List<Map.Entry<String, String>> infos = new ArrayList<Map.Entry<String, String>>(map.entrySet());
    
            // 重写集合的排序方法:按字母顺序
            Collections.sort(infos, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(final Entry<String, String> o1, final Entry<String, String> o2) {
                    return (o1.getKey().toString().compareTo(o2.getKey()));
                }
            });
    
            return infos;
        }
    
        public static void main(final String[] args) {
            final Map<String, String> map = new HashMap<String, String>();
            map.put("charSet", "utf-8");
            map.put("merId", "5412");
            map.put("acqId", "321");
    
            final List<Map.Entry<String, String>> list = new MapSort().sortMap(map);
    
            for (final Map.Entry<String, String> m : list) {
                System.out.println(m.getKey() + ":" + m.getValue());
            }
    
        }
    
    }

    执行main方法,结果如下:

    acqId:321
    charSet:utf-8
    merId:5412
  • 相关阅读:
    AngularJs 1.x和AngularJs2的区别
    AngularJS ui-router (嵌套路由)
    $scope.$apply
    AngularJS中的$watch(),$digest()和$apply()区分
    对比jQuery和AngularJS的不同思维模式
    angular.element 动态添加和删除元素
    [Leetcode] Integer to Roman
    [Leetcode] Longest Common Prefix
    [Leetcode] Plus One
    [Leetcode] Palindrome Number
  • 原文地址:https://www.cnblogs.com/shindo/p/5900472.html
Copyright © 2020-2023  润新知