Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map with keys of 3 columns

I need a map in which my key should be based on 3 columns, say C1, C2, C3. C1 has highest priority. C2 has one less than C1 and C3 has one less than C2.

How do i create key in the map such that if somebody asks for information on C1, I should able to give all the values which has C1. I also should be able to return all the values if asked for C1 & C2

like image 821
Avinash Avatar asked Mar 21 '13 06:03

Avinash


1 Answers

You can use the same strategy as multicolumn indexes in databases, if your key columns can be ordered (i.e., in Java, they need to be Comparable) and can easily define maximum and minimum values for all but the first.

An example with integer columns:

public class Key implements Comparable<Key> {
    int c1, c2, c3;

    private static final int c2_min = Integer.MIN_VALUE;
    private static final int c2_max = Integer.MAX_VALUE;
    private static final int c3_min = Integer.MIN_VALUE;
    private static final int c3_max = Integer.MAX_VALUE;

    @Override
    public int compareTo(Key o) {
        if (c1!=o.c1) return Integer.compare(c1, o.c1);
        if (c2!=o.c2) return Integer.compare(c2, o.c2);
        return Integer.compare(c3, o.c3);
    }

    // constructor, equals, ...

}

and then you can get all entries for some value k1 in c1 like this:

map.subMap(new Key(k1, Key.c2_min, 0), new Key(k1, Key.c2_max, 0));

Likewise, using the first two columns:

map.subMap(new Key(k1, k2, Key.c3_min), new Key(k1, k2, Key.c3_max));
like image 159
jop Avatar answered Sep 30 '22 16:09

jop