java中,map集合排序实例

来源:互联网 发布:淘宝足球 编辑:程序博客网 时间:2024/06/05 23:08

1.实体类

package test;
/**
 * 学生实体类
 * @author xf
 *
 */
public class Student {
    private String name;
    private int avg;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAvg() {
        return avg;
    }
    public void setAvg(int avg) {
        this.avg = avg;
    }
}


2.map集合排序实现类

package test;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 * map集合排序
 * @author xf
 *
 */
public class MapKeyComparator implements Comparator<String>  {
    @Override
    public int compare(String str1, String str2) {
        int num=str1.compareTo(str2);
        if(num>0){  //降序
            return -1;
        }else{
            return 1;
        }
        /*if(num>0){  //升序
            return 1;
        }else{
            return -1;
        }*/
    }

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


3.测试类

package test;

import java.util.HashMap;
import java.util.Map;

public class Test_sdgd {
    public static void main(String[] args) {
        try {
            Map<String, Student> map = new HashMap<String, Student>();
            map.put("2009", new Student());
            map.put("2016", new Student());
            map.put("2005", new Student());
            map.put("2001", new Student());
            map.put("2014", new Student());
            map.put("2011", new Student());
            map.put("2010", new Student());
            map.put("2012", new Student());
            map=MapKeyComparator.sortMapByKeyStu(map);
            for (Map.Entry<String, Student> entry : map.entrySet()) {
                System.out.println(entry.getKey());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


0 0
原创粉丝点击