排序HashMap的基础上,从价值

问题描述:

有一类排序HashMap的基础上,从价值

class Employee { 
    int id; 
    String name; 
} 

和一个

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

现在我想整理上述map一个Employee's name在此基础上包含该值的对象映射。意思是当我使用Map.EntryEmployee迭代这张地图时,对象必须按字母顺序进行检索。

在此先感谢

+0

发布您尝试过的样品。 – subodh 2013-03-21 07:34:24

+0

我没有试过。我只是搜索这个需求,但没有找到任何相同的职位。 – Navnath 2013-03-21 07:37:43

+0

我想你可以在这篇文章中找到你的答案:[如何排序地图对Java的价值?](http://*.com/questions/109383/how-to-sort-a-mapkey-value -in-the-values-in-java) – 2013-03-21 07:42:25

Michaël建议一个链接是Sort a Map<Key, Value> by values (Java)。我做了一些改变。它适用于我

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; 
    } 
} 

有关解决方案,请参考以上的内容链接。

感谢所有有答复的人。

+0

这种方法是合同式的,可以根据键进行排序。 – NilsH 2013-03-21 07:48:22

+0

@NilsH:由于它允许自定义比较器,因此您可以编写自己的逻辑进行排序。 – anubhava 2013-03-21 07:53:02

+0

是的,你可以,但重点在于它是按键排序的。 – NilsH 2013-03-21 08:17:53

您不能对一个HashMap,但你可以entrySet()获得其条目排序。

public class MapSort { 
    private static class Employee { 
     public String name; 

     public Employee(String name) { 
      this.name = name; 
     } 

     @Override 
     public String toString() { 
      return name; 
     } 
    } 

    public static void main(String[] args) { 
     Map<Integer, Employee> map = new HashMap<Integer, Employee>(); 

     map.put(1, new MapSort.Employee("x")); 
     map.put(2, new MapSort.Employee("a")); 
     map.put(3, new MapSort.Employee("f")); 

     List<Map.Entry<Integer, Employee>> entryList = new ArrayList<Map.Entry<Integer, Employee>>(map.entrySet()); 

      Collections.sort(
        entryList, new Comparator<Map.Entry<Integer, Employee>>() { 
       @Override 
       public int compare(Map.Entry<Integer, Employee> integerEmployeeEntry, 
            Map.Entry<Integer, Employee> integerEmployeeEntry2) { 
        return integerEmployeeEntry.getValue().name 
          .compareTo(integerEmployeeEntry2.getValue().name); 
       } 
      } 
     ); 

     System.out.println(entryList); 
    } 
} 

排序,你可以把你的背部条目,支持排序的地图,例如LinkedHashMap后。

这取决于你的用例:如果你需要保持地图总是排序,那么使用TreeMap会带来额外的开销。如果您只需要一次排序,则可以使用带有上述代码的HashMap