Skip to content

Espresso for Java – boost your productivity with inline arrays, lists, and maps

Java 8 lies ahead and with it promises of native Collection support. But that’s a while away, we want it now! And with Espresso4J, a small language-augmenting library designed to put a shot of liveliness into Java syntax, we can have it now too.

How often have we been frustrated with Java’s verbosity when we just want a quick inline array, list, set, or map on the fly? The language should have such a construct and now it can! Take the classic List example:

//Building a List of Strings the usual way
 
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

It’s rather cumbersome, no? Lets try this again using Espresso4J:

//Building a List of Strings with Espresso4J
 
List<String> list = list("a", "b", "c");

And that’s it. That’s it? That’s it! Boilerplate method calls removed, automated type inference, and a compact and intuitive syntax.

How about arrays? Java does have native support for inline arrays, but only when being immediately assigned: String[] = {"a", "b", "c"}; is valid but not foo({"a", "b", "c"});

public void foo(String[] array){}

foo({"a", "b", "c"}); //Illegal

//Building an array of Strings with Espresso4J
foo( array("a", "b", "c") ); //Legal using Espresso4J

I mentioned maps, lets do that one!

//Building a Map of Strings to Integers with Espresso4J
 
Map<String, Integer> map = map( pair("one", 1), pair("two", 2) );

Alright, I’ll admit that inline maps are a bit more verbose as it relies on pair(), another pseudo-construct that Espresso4J brings but you must admit that it’s still clean and intuitive. Inline collection types is wildly exciting, a feature Java should have had a long time ago. Go ahead, grab Espresso4J and lighten your code today!