I am the founder and CEO of Data Geekery GmbH, located in Zurich, Switzerland. With our company, we have been selling database products and services around Java and SQL since 2013. Ever since my Master's studies at EPFL in 2006, I have been fascinated by the interaction of Java and SQL. Most of this experience I have obtained in the Swiss E-Banking field through various variants (JDBC, Hibernate, mostly with Oracle). I am happy to share this knowledge at various conferences, JUGs, in-house presentations and on our blog. Lukas is a DZone MVB and is not an employee of DZone and has posted 249 posts at DZone. You can read more from them at their website. View Full User Profile

Array, List, Set, Map, Tuple, Record Literals in Java

06.06.2012
| 13845 views |
  • submit to reddit

Occasionally, when I’m thrilled by the power and expressiveness of JavaScript, I find myself missing one or two features in the Java world. Apart from lambda expressions / closures or whatever you want to call “anonymous functions”, it’s the use of advanced literals for common data types, such as arrays, lists, sets, maps, etc. In JavaScript, no one would think about constructing a constant Map like this:

var map = new Object();
map["a"] = 1;
map["b"] = 2;
map["c"] = 3;

Instead, you’d probably write

var map = { "a":1, "b":2, "c":3 };

Specifically, when passing complex parameters to an API function, this turns out to be a very handy syntax.

What about these things in Java?

I’ve recently posted about a workaround that you can use for creating a “List literal” using Arrays.asList(…) here:

http://blog.jooq.org/2011/10/28/javas-arrays-aslist-is-underused/

This is somewhat OK. You can also construct arrays when you assign them, using array literals. But you cannot pass an array literal to a method:

// This will work:
int[] array = { 1, 2, 3 };

// This won't:
class Test {
  public void callee(int[] array) {}
  public void caller() {
    // Compilation error here:
    callee({1, 2, 3});
  }
}

Brian Goetz’s mentioning of various literals on lambda-dev

Missing this feature for quite a while, I was very thrilled to read Brian Goetz’s mentioning of them on the lambda-dev mailing list:

http://mail.openjdk.java.net/pipermail/lambda-dev/2012-May/004979.html

The ideas he was listing were these:

#[ 1, 2, 3 ]                          // Array, list, set
#{ "foo" : "bar", "blah" : "wooga" }  // Map literals
#/(\d+)$/                             // Regex
#(a, b)                               // Tuple
#(a: 3, b: 4)                         // Record
#"There are {foo.size()} foos"        // String literal

Unfortunately, he also added the following disclaimer:

Not that we’d embrace all of these immediately (or ever)

Obviously, at this stage of current Java language evolvements for Java 8, he cannot make any guarantee whatsoever about what might be added in the future. But from a jOOQ perspective, the idea of being able to declare tuple and record literals (with the appropriate backing language-support for such types!) is quite thrilling. Imagine selecting arbitrary tuples / records with their associated index/type, column/type pairs. Imagine a construct like this one in Java or Scala (using jOOQ):

// For simplicity, I'm using Scala's val operator here,
// indicating type inference. It's hard to guess what true
// record support in the java language should look like
for (val record : create.select(
                           BOOK.AUTHOR_ID.as("author"), 
                           count().as("books"))
                        .from(BOOK)
                        .groupBy(BOOK.AUTHOR_ID)
                        .fetch()) {
  
   // With true record support, you could now formally extract
   // values from the result set being iterated on. In other
   // words, the formal column alias and type is available to
   // the compiler:
   int author = record.author;
   int books = record.books;
}

Obviously, this is only speculation, but you can see that with true tuple / record support in the Java language, a lot of features would be unleashed in the Java universe with a very high impact on all existing libraries and APIs

Stay tuned! :-)

 

 

 

 

Published at DZone with permission of Lukas Eder, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Erwin Mueller replied on Sat, 2012/06/09 - 4:37am

callee(new int[] {1, 2, 3}); Wow that was so hard to do :p sql = "select book.author_id as author, count(books) from book group by book.author_id"; for (Record record : create.select(sql) { int author = record.getInt("author"); int books = record.getInt("books"); } I really do not understand the new trend in putting everything in the language. I mean, really, how often will you use arrays, sets, tuples, etc. as literals? The 99% of use cases are that you create an array or set and fill it with data later. As for tuples: I rather have something like foo.getFirstName(), foo.getLastName() as foo[0] and foo[1]. At least with the first expression I know what I get and don't have to guess if foo[0] was the first or the last name. Furthermore, do you really enjoy writing something like create.select( BOOK.AUTHOR_ID.as("author"), count().as("books")) .from(BOOK) .groupBy(BOOK.AUTHOR_ID) .fetch() and maybe more method chains? Why not just the SQL query string, with is perfectly good for expressing a SQL query? At least the SQL query string is perfectly understandable, inter operate and expandable. Also I don't have to write so many (-) and ", I can just write English. Java language, a lot of features would be unleashed in the Java universe with a very high impact on all existing libraries and APIs Yes I'm afraid so. I don't really think it is a good thing to put everything in the language syntax. I'm from the school of "use the right tool for the right job". And the Java language (or any C-like language) is not a good tool for writing SQL queries, no matter how much you try to argue, "but but C# have LINQ with is sooooo much better". PS: I'm right now really biased against JS developers. They bring us joy everyday like the rich-text comment field in DZone. Which of course is on the good days half broken and on the bad days do not work at all (like right now). How about you JS developers first get us a working rich-text comment field and then we can talk about "enhancing" our languages in which we do some real work?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.