开发者

Sorting a HashMap with 2 fields

I have a hashmap with 8 fields. Among those 2 are id and idseq. Both are integer. There can be more than one similar idseq, but no开发者_如何转开发t for one id. Can this hasp map be sorted on the basis of these 2?


Create a key containing these two integer values and use that as a key for your map. Make this key Comparable and implement your sorting logic there.

Something like this:

class MyCustomKey implements Comparable<MyCustomKey> {
    final int id;
    final int idSeq;

    public MyCustomKey(int id, int idSeq) {
        this.id = id;
        this.idSeq = idSeq;
    }

    public int getId() {
        return this.id;
    }

    public int getIdSeq() {
        return this.idSeq;
    }

    @Override
    public int compareTo(MyCustomKey o) {
        // your compare logic goes here
        return -1;
    }
}

You can then use this as the key for your map, preferably a TreeMap if it should be sorted.


Use a TreeMap instead with custom Comparator which you should pass to its constructor.


We can use a Tree map like this:

TreeMap<Integer,DRG> sortedMap = new TreeMap<Integer,DRG>();

 sortedMap.putAll(hashmap);

Treemap will take care of the rest. The order of values as represented in the database can be restored by using a Tree map.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜