Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


SQL Simplicity for Java Value Mapping : Page 3

When you have a cascading map in Java, which index goes first and how do you scan the whole collection? Use Java maps that have two sets of keys.


WEBINAR: On-Demand

Unleash Your DevOps Strategy by Synchronizing Application and Database Changes REGISTER >

What Would a SQL Programmer Do?
A SQL programmer would have a Collection<Event> and, when specified, would also have the necessary indexes automatically updated on all changes. Maybe you could imitate this behavior. What if, in addition to the interface Map<X,Y> (which has been around since the mammoth times), you introduce one more key—just one more—and have a new interface, Map<X,Y,V>, where X and Y are key types and V is a value type? The following code is almost the same as Map<X,Y> but the entries have two keys, so you would have two sets of keys:

public interface Map2<X,Y,V> { int size(); boolean containsKeyPair(Object key1, Object key2); V get(X key1, Y key2); V put(X key1, Y key2, V value); V remove(X key1, Y key2); Set<X> keySet1(); Set<Y> keySet2(); Collection<V> values(); Map<Y,V> curry1(X key1); Map<X,V> curry2(Y key2); interface Entry<X,Y,V> { public X getKey1(); public Y getKey2(); public V getValue(); V setValue(V value); } Set<Map2.Entry<X,Y,V>> entrySet(); }

Note two new methods, curry1 and curry2. They take one key and return a map from another key to values. The names come from currying, the functional programming term for this operation.

A default implementation, AbstractMap2<X,Y,V>, stores entries in a set, and retrieval of a value for a pair of keys amounts to scanning through the whole set of entries, which for small sets may not be bad at all. The only abstract method here is Set<Map2.Entry<X,Y,V>> entrySet(), which gives you the freedom to store the data any way you choose.

The default implementation is not very efficient, so let's introduce an indexed map: IndexedMap2<X,Y,V>. This map maintains two indexes, for X and for Y, and Set<Map2.Entry<X,Y,V>> entrySet() remains abstract.

Two-Parameter Maps
As you have read, a relatively small group of classes solves a rather frequent problem: when you have a cascading map, which index goes first and how do you scan the whole collection? You could adapt the classes you know, Map and Set, by always designating whether hunters go first and own a collection of time-indexed events, or whether time goes first and each moment has a collection of hunter-indexed events. But the better solution is applying Map2, a map with two sets of keys.

Vlad Patryshev is an R&D engineer at the Java Business Unit of Borland. He recently started the myjavatools.com project.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date