开发者

Sorting HashMap objects on their properties rather values [duplicate]

开发者 https://www.devze.com 2023-03-10 16:47 出处:网络
This question already has answers here: Sort a Map<Key, Value> by values (64 answers) Sorting Java objects using multiple keys
This question already has answers here: Sort a Map<Key, Value> by values (64 answers) Sorting Java objects using multiple keys 开发者_运维知识库 (7 answers) Closed 3 years ago.

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


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.


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消