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


SQL Simplicity for Java Value Mapping

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 Event

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

ava does not have a convenient way to treat a function as an object and then pass it around, but suppose it could. Say a function were an implementation of the following interface:

interface Function<X,Y> { Y apply(X x); }

This may not be as convenient as what Python, Ruby, or JavaScript offers, but it gives the programmer a new dimension. For instance, you could apply a function to a collection, element-wise, and produce another collection. (Functional programming has special terms for such an operation, but this example is in Java, so let's not make things too complicated.)

In a sense, Map<X,Y> is very similar to Function. The main difference is that a map has a predefined set of keys, while a function is defined on the whole range of type values. With a Map<X,Y>, you can easily build a function based on that map:

Function<X,Y> function(Map<X,Y> map) { return new Function<X,Y>() { public Y apply(X x) { return map.get(x); } } }

For the argument values that are not in the list of map keys, the function will return null. You could modify function() to take the second parameter, the default value for the function.

On the other hand, if you have a Function<X,Y>, you need a Set<X> of keys to build a Map<X,Y> that corresponds to that function. But in essence, a Map<X,Y> is very different from a Function<X,Y>. When you create a map, you provide a collection of facts: certain keys are connected with certain values. You can add or remove these facts from the knowledge, and if, for a given key, a map produces a value associated with the key, it is just a convenience—like a select...where statement in SQL, it facilitates knowledge retrieval.

This article introduces maps that have two sets of keys, and shows how useful this class can be in everyday Java coding.

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