根据属性而不是值对 HashMap 对象进行排序

发布于 2024-11-13 11:41:03 字数 618 浏览 2 评论 0原文

这不是我刚刚模拟的真实代码,以便了解下一步该做什么。

我有一个具有年龄、身高、体重属性的 Person 类。
现在在我的班级小组
我创建了两个四个对象

Person programmer, student, clerk, tech;

,我有 HashMap rollCall

Map<Person, Integer> rollCall = new HashMap<Person, Integer>();

使用 Person 和人员数量作为 Integer 类型来添加所有这些对象

rollCall.put(programmer, 1);
rollCall.put(clerk, 2);
rollCall.put(student, 1);
rollCall.put(tech, 3);

我看到很多人使用 TreeMap 对 HashMap 进行排序 我想对 Person 的属性进行排序关于价值。我想按年龄对所有这些人进行排序(即programmer.getAge();)。我不确定是否会使用仅适用于集合而非地图的比较器。 。 请帮忙... 。

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 programmer, student, clerk, tech;

I have HashMap rollCall

Map<Person, Integer> rollCall = new HashMap<Person, Integer>();

to add all these using Person and number of Persons as type Integer

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 ...
.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

睡美人的小仙女 2024-11-20 11:41:03

您可以获得一个 Map,它通过使用自定义比较器按年龄递增或递减顺序进行迭代:

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

当您将 Persons 添加到集合中时,它们将按年龄顺序插入。

You can get a Map<Person,Integer> which iterates by age increasing or decreasing order by using a custom comparator:

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.

风轻花落早 2024-11-20 11:41:03

您需要能够比较您的 Person 对象。如果有规范的方法来比较它们,请让它们实现 Comparable(即给它们一个 compareTo(Person) 方法。

如果完成了,您可以使用将 person 作为 SortedMap(如 TreeMap)的键。

如果可以通过多种方式比较两个人,请实现一个 Comparator作为单独的对象,

然后在构造时将此比较器提供给 SortedMap 。这不会对你

的 HashMap 进行排序(HashMap 总是具有看似随机的顺序),而是为你提供另一个排序的数据结构。

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.

If this is done, you can use the persons as keys for a SortedMap (like TreeMap).

If there are multiple ways two persons could be compared, implement a Comparator<Person> as a separate object.

Then give this comparator to the SortedMap on construction.

This will not sort your HashMap (a HashMap has always a seemingly random order), but give you another sorted datastructure instead.

不甘平庸 2024-11-20 11:41:03

首先,TreeMap 按键排序,而不是按值排序。所以这已经对你有利了。在 TreeMap 中用作键的任何对象必须实现 Comparable,或者您必须提供一个 Comparator 作为构造函数参数。您所需要做的就是使用 compareTo() 方法(来自 Comparable)或 compare() 方法(来自 Comparator code>) 根据您的 getAge() 属性进行比较。

此处。 Comparator 将用于对映射中的键进行排序。

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 must implement 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.

The TreeMap constructor that takes a Comparator is described here. The Comparator will be used to sort the keys in the map.

温柔戏命师 2024-11-20 11:41:03
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();
    }
}
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();
    }
}
抱着落日 2024-11-20 11:41:03
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;
    }    
}
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;
    }    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文