Dollar - Java API that unifies collections, arrays, iterators/iterable, and char sequences

Dollar¬†says it’s a “Java API that unifies collections, arrays, iterators/iterable, and char sequences”, but it’s actually much more. I randomly found it while exploring bitbucket and immediately found it interesting.

Much like jQuery, it utilizes the $ symbol, which although not acceptable by Java naming conventions, is a valid Java name and makes for concise and readable code. In addition to unifying Collections and arrays, it also adds many useful methods that you might find in other languages, like “join”, “slice”, “repeat”, “concat”, “reverse” and many others.

Here’s some example code pulled from the dollar wiki:

import static com.humaorie.dollar.Dollar.*;
// yes, $ is a valid Java identifier! 
// build the list [0, 1, 2, 3, 4]
List<Integer> list = $(5).toList();

// build the list [10, 11, 12, 13, 14]
List<Integer> list2 = $(10, 15).toList();

// build a sorted random list of 50 integers up to 100
List<Integer> randomIntegers = $(new Random(), 100).samples(50).sort().toList();
// build the String "4->3->2->1->0" 

// repeat a String
String repeat = $("abc").repeat(3).join(" "); // "abc abc abc"

// convert and sort a Long[] to long[] 
Long[] aLongArray = { 42L, 84L };
long[] longs = $(aLongArray).sort().toLongArray();

// fluent interface: convert a primitive int array to java.util.List, in the reversed order
int[] array = { 4, 2, -5 };
List<Integer> list = $(array).sort().reverse().toList();

// you can even unbox a short[] array to long[] (since it doesn't cause a loss of precision)
short[] shorts = { 42, 42, 42 };
long[] $(shorts).toLongArray();
I've also added some additional functionality that Davide pulled:
  1. Date Ranges: $(begin, end)
  2. Lazy filtering and mapping
  3. A bunch of additional core methods: min, max, each, any, all, find, indexOf, reduce
  4. asPredicate() method for determining membership (might be removed in the future)

If you’re a Java developer who wishes the Java API was more consistent and more functional with arrays, lists, sets, string, etc, then check it out.

Tags: java dollar