To sort by Value value (object) in TreeMap

Asked 2 years ago, Updated 2 years ago, 53 views

Hi, everyone. Post a question while studying the collection framework.

When you convert HashMap to TreeMap, it is automatically sorted by the key value.

HashMap<String, GameScore> map = new HashMap<String, GameScore>();
...
TreeMap<String, GameScore> tMap = new TreeMap<String, GameScore>(map);
System.out.println("==" + tMap.values());
Results:
[Kang Gam Chan, 65200, Yi Sun Shin, 57800, Lim Kkeokjeong, 51890, Jang Gil San, 68000, Hong Gil Dong, 72680]

My question is, This is about how to sort by the class's property value (int) when TreeMap is given a reference value of an object (class instance) as a value value.

I searched and found a way to override the comparator using SortedSet. If it is correct to use the same method in HashMap or TreeMap, please explain it in detail. Or it would be more helpful if you could post a related example.

For reference, the object corresponding to value inherited the comparable interface and overridden the comareTo method as follows.

class GameScore implements Comparable<Object> {
    private String name;
    private int score;
    ....
    @Override
    public int compareTo(Object o) {
        GameScore gs = (GameScore) o;
        return (this.score < gs.score ? -1 :(this.score == gs.score ? 0 : 1));
    }
}

java

2022-09-21 18:40

1 Answers

class GameScore implements Comparable<GameScore> { 
    // Put yourself in the Generic of Comparable.
    private String name;
    private int score;
    ....
    @Override
    public int compareTo(GameScore gs) {
        // If it's equal to 0,
        // If the current object is less than gs -1
        // 1 if the current object is greater than gs
        // So I think it's written correctly.
        return (this.score < gs.score ? -1 :(this.score == gs.score ? 0 : 1));

        // If you're not sure, you can box to the Integer class and then use compareTo. 
        // // Integer ts = score;
        // // Integer rs = gs.score;
        // // return ts.compareTo(rs);
    }
}

Try fixing it like above.

And TreeMap sorts for Key. If you need an alignment for Value, write TreeSet, or

List<GameScore> list = new ArrayList<>(map.values()); // JAVA 8 can use this.
Collections.sort(list); // java.util.Collections

Put it in the list as shown above and sort it using the Collections.sort function.


2022-09-21 18:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.