根据对象的成员变量从值对HashMap进行排序 [英] Sort HashMap basis on Object's member variable from value

查看:54
本文介绍了根据对象的成员变量从值对HashMap进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一堂课

class Employee {
    int id;
    String name;
}

和一张包含此对象值的地图

and one map which contains this object in value

Map<Integer, Employee> map = new HashMap<Integer, Employee>();

现在,我想在 map 上方对雇员姓名的依据之一进行排序.意味着当我使用 Map.Entry 迭代此地图时, Employee 对象必须按字母顺序检索.

Now I want to sort above map one the basis of Employee's name. Means when I iterate this map using Map.Entry, Employee objects must retrive alphabetically.

预先感谢

推荐答案

Michaël建议使用一个链接,该链接为.我做了一些更改.对我有用

Michaël suggested one link which is Sort a Map<Key, Value> by values (Java) . I did some change in it. and it works for me

class ValueComparator implements Comparator<Integer> {

    Map<Integer, Employee> base;
    public ValueComparator(Map<Integer, Employee> base) {
        this.base = base;
    }

    // Note: this comparator imposes orderings that are inconsistent with equals.    
    public int compare(Integer a, Integer b) {
        return ((Employee)base.get(a)).compareTo(base.get(b));
    }

}

class Employee implements Comparable {
    public String name;
    public int id;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Object obj) {
        return this.name.compareTo(((Employee)obj).name);
    }

    public String toString() {
        return name;
    }
}

有关解决方案,请也参考上面的链接.

For solution please refere above mension link too.

感谢所有答复.

这篇关于根据对象的成员变量从值对HashMap进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆