JavaBits
JavaBits

Reputation: 2055

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 not for one id. Can this hasp map be sorted on the basis of these 2?

Upvotes: 0

Views: 209

Answers (3)

JavaBits
JavaBits

Reputation: 2055

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.

Upvotes: 0

wjans
wjans

Reputation: 10115

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.

Upvotes: 1

Roman
Roman

Reputation: 66186

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

Upvotes: 0

Related Questions