java 根据其属性而不是值对 HashMap 对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6259677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting HashMap objects on their properties rather values
提问by Aahil
This is not my real code I have just simulated in order to understand what to do next.
I have class Person with properties age, height weight.
Now In my class Group
I create two four objects
这不是我为了了解下一步要做什么而模拟的真实代码。
我有一个具有年龄、身高体重属性的 Person 类。
现在在我的班级 Group
我创建了两个四个对象
Person programmer, student, clerk, tech;
I have HashMap rollCall
我有 HashMap rollCall
Map<Person, Integer> rollCall = new HashMap<Person, Integer>();
to add all these using Person and number of Persons as type Integer
使用 Person 和 Number of Persons 作为整数类型添加所有这些
rollCall.put(programmer, 1);
rollCall.put(clerk, 2);
rollCall.put(student, 1);
rollCall.put(tech, 3);
I have seen alot of people sorting HashMap using TreeMap on value I want to sort on a property of Person rather on value. I want to sort all these people on their age (i.e. programmer.getAge();). I am not sure if I will use comprator which works only on collection not map. . Please help ... .
我见过很多人使用 TreeMap 根据值对 HashMap 进行排序,我想根据 Person 的属性而不是值进行排序。我想按年龄对所有这些人进行排序(即程序员.getAge();)。我不确定我是否会使用仅适用于集合而非地图的比较器。. 请帮忙 ... 。
回答by maerics
You can get a Map<Person,Integer>
which iterates by age increasing or decreasing order by using a custom comparator:
您可以Map<Person,Integer>
使用自定义比较器获得按年龄递增或递减顺序迭代的 a :
Map<Person, Integer> rollCall = new TreeMap<Person, Integer>(
new Comparator<Person>() {
@Override public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge(); // Acending.
// or p2.getAge() - p1.getAge(); // Descending.
}
}
);
When you add Persons to the collection they will be inserted in order by age.
当您将 Person 添加到集合中时,它们将按年龄顺序插入。
回答by Ernest Friedman-Hill
First of all, TreeMap
sorts on keys, not values. So that's already working in your favor. Any object you use as a key in a TreeMap
mustimplement Comparable
, or you must provide a Comparator
as a constructor argument. All you need to do is have your compareTo()
method (from Comparable
) or compare()
method (from Comparator
) compare based on your getAge()
property.
首先,TreeMap
按键排序,而不是按值排序。所以这已经对你有利了。您在 a 中用作键的任何对象都TreeMap
必须实现Comparable
,或者您必须提供 aComparator
作为构造函数参数。您需要做的就是根据您的财产比较您的compareTo()
方法 (from Comparable
) 或compare()
方法 (from Comparator
) getAge()
。
The TreeMap
constructor that takes a Comparator
is described here.The Comparator
will be used to sort the keys in the map.
回答by Pa?lo Ebermann
You need to be able to compare your Person objects. If there is a canonical way to compare them, let them implement Comparable<Person>
(i.e. give them a compareTo(Person)
method.
您需要能够比较您的 Person 对象。如果有比较它们的规范方法,让它们实现Comparable<Person>
(即给它们一个compareTo(Person)
方法。
If this is done, you can use the persons as keys for a SortedMap (like TreeMap).
如果这样做,您可以使用人作为 SortedMap(如 TreeMap)的键。
If there are multiple ways two persons could be compared, implement a Comparator<Person>
as a separate object.
如果有多种方法可以比较两个人,请将 a 实现Comparator<Person>
为单独的对象。
Then give this comparator to the SortedMap on construction.
然后在构造时将此比较器提供给 SortedMap。
This will not sort your HashMap (a HashMap has always a seemingly random order), but give you another sorted datastructure instead.
这不会对您的 HashMap 进行排序(HashMap 总是看似随机的顺序),而是为您提供另一个已排序的数据结构。
回答by Saurabh Kachhia
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class PersonSort {
private MySort sort = new MySort();
private Map<Person, String> map = new HashMap<Person, String> ();
private Map<Person, String> treeMap = new TreeMap<Person, String>(sort);
Person e1 = new Person(500, "Saurabh");
Person e2 = new Person(400, "Kishan");
Person e3 = new Person(900, "Ashwini");
public void myMap() {
map.put(e3, "Ash");
map.put(e2, "Krish");
map.put(e1, "Sau");
Iterator it = map.keySet().iterator();
System.out.println("UnSorted Map");
while(it.hasNext()) {
System.out.println(map.get(it.next()));
}
treeMap.putAll(map);
System.out.println("SortedMap");
Iterator it1 = treeMap.keySet().iterator();
while(it1.hasNext()) {
System.out.println(treeMap.get(it1.next()));
}
}
public static void main(String[] args) {
PersonSort es = new PersonSort();
es.myMap();
}
}
class Person {
Person(int id, String name) {
this.id = id;
this.name = name;
}
private int id;
private String name;
//Getters and Setters
}
class MySort implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return ((Person) o1).getId() - ((Person)o2).getId();
}
}
回答by utpal kanta kar
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/*
* Sort HashMap that contains Student object
*/
public class SortHashMap implements Comparator<Student>
{
public static void main(String[] args)
{
Map map = new HashMap();
map.put("s1", new Student(5,"utpal"));
map.put("s2", new Student(4,"ramesh"));
map.put("s3", new Student(10,"tushar"));
map.put("s4", new Student(2,"anindya"));
Collection<Student> students = map.values();
List list = new ArrayList(students);
Collections.sort(list,new SortHashMap());
for (Iterator it = list.iterator(); it.hasNext();)
{
Student stdn = (Student)it.next();
System.out.println("Student id : "+stdn.id);
System.out.println("Student Name : "+stdn.name);
}
}
@Override
public int compare(Student s1, Student s2)
{
return s1.name.compareTo(s2.name);
}
}
class Student
{
int id;
String name;
Student(int id,String name)
{
this.id = id;
this.name = name;
}
}