Underscore-java

Underscore-java is a port of Underscore.js for Java. It is a utility-belt library that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby).

Underscore-java provides dozens of functions that support both the usual functional suspects: map, select, invoke - as well as more specialized helpers: function binding, sorting, deep equality testing, and so on. It delegates to built-in functions where applicable.

Underscore-java is compatible with Java 6 and later.

The project is hosted on GitHub. Contributions are welcome.

Download

Version 1.23 - ~4.9Mb, Includes all development files

Collection Functions (Arrays, Structs, Queries, or Objects)

each $.each(collection, iterator)
Iterates over a collection of elements, yielding each in turn to an iterator function. The iterator is bound to the context object (component or struct), if one is passed. Each invocation of iterator is called with argument: (element).

$.each(asList(1, 2, 3), new Block<Integer>() {
    public void apply(Integer item) {
        System.out.println(item + ",");
    }
});
// 1,2,3,

int multiplier = 2;
int index = 0;
$.each(asList(1, 2, 3), new Block<Integer>() {
    public void apply(Integer item) {
        System.out.println(index + "=" + (item * multiplier) + ",");
        index += 1;
    }
});
// 0=2,1=4,2=6,

map $.map(collection, iterator)
Produces a new array of values by mapping each value in collection through a transformation function (iterator).

$.map(asList(1, 2, 3), new Function1<Integer, Integer>() {
    public Integer apply(Integer item) {
        return item * 3;
    }
});
// [3, 6, 9]

$.map(new LinkedHashMap<Integer, String>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}
    .entrySet(),
    new Function1<Map.Entry<Integer, String>, Integer>() {
    public Integer apply(Map.Entry<Integer, String> item) {
        return item.getKey() * 3;
    }
});
// [3, 6, 9]

reduce $.reduce(collection, iterator, memo)
Also known as inject and foldl, reduce boils down a collection of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iterator.

$.reduce(asList(1, 2, 3),
    new FunctionAccum<Integer, Integer>() {
    public Integer apply(Integer item1, Integer item2) {
        return item1 + item2;
    }
    },
    0
);
// 6

reduceRight $.reduceRight(collection, iterator, memo)
The right-associative version of reduce.

$.reduceRight(asList(asList(0, 1), asList(2, 3), asList(4, 5)),
    new FunctionAccum<List<Integer>, List<Integer>>() {
    public List<Integer> apply(List<Integer> item1, List<Integer> item2) {
        List<Integer> list = new ArrayList<Integer>(item1);
        list.addAll(item2);
        return list;
    },
    Collections.<Integer>emptyList()
});
// [4, 5, 2, 3, 0, 1]

find $.find(collection, iterator)
Looks through each value in the collection, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire collection.

$.find(asList(1, 2, 3, 4, 5, 6),
    new Predicate<Integer>() {
    public Boolean apply(Integer item) {
        return item % 2 == 0;
    }
}).get();
// 2

filter $.filter(collection, iterator)
Looks through each value in the collection, returning an array of all the values that pass a truth test (iterator).

$.filter(asList(1, 2, 3, 4, 5, 6),
    new Predicate<Integer>() {
    public Boolean apply(Integer item) {
        return item % 2 == 0;
    }
});
// [2, 4, 6]

where $.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

class Book {
    public final String title;
    public final String author;
    public final Integer year;
    public Book(final String title, final String author, final Integer year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }
    public String toString() {
        return "title: " + title + ", author: " + author + ", year: " + year;
    }
}
List<Book> listOfPlays =
    new ArrayList<Book>() { {
      add(new Book("Cymbeline2", "Shakespeare", 1614));
      add(new Book("Cymbeline", "Shakespeare", 1611));
      add(new Book("The Tempest", "Shakespeare", 1611));
    } };
$.where(listOfPlays, asList(
            Tuple.<String, Object>create("author", "Shakespeare"),
            Tuple.<String, Object>create("year", Integer.valueOf(1611))));
// [title: Cymbeline, author: Shakespeare, year: 1611,
title: The Tempest, author: Shakespeare, year: 1611]

findWhere $.findWhere(collection, properties)
Looks through the collection and returns the first value that matches all of the key-value pairs listed in properties.

class Book {
    public final String title;
    public final String author;
    public final Integer year;
    public Book(final String title, final String author, final Integer year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }
    public String toString() {
        return "title: " + title + ", author: " + author + ", year: " + year;
    }
}
List<Book> listOfPlays =
    new ArrayList<Book>() { {
      add(new Book("Cymbeline2", "Shakespeare", 1614));
      add(new Book("Cymbeline", "Shakespeare", 1611));
      add(new Book("The Tempest", "Shakespeare", 1611));
    } };
$.findWhere(listOfPlays, asList(
    Tuple.<String, Object>create("author", "Shakespeare"),
    Tuple.<String, Object>create("year", Integer.valueOf(1611)))).get();
// "title: Cymbeline, author: Shakespeare, year: 1611"

reject $.reject(collection, iterator)
Returns the values in collection without the elements that the truth test (iterator) passes. The opposite of filter.

$.reject(asList(1, 2, 3, 4),
    new Predicate<Integer>() {
    public Boolean apply(Integer item) {
        return item % 2 == 0;
    }
});
// [1, 3]

all $.all(collection, iterator)
Returns true if all of the values in the collection pass the iterator truth test.

$.all(asList(1, 2, 3, 4),
    new Predicate<Integer>() {
        public Boolean apply(Integer item) {
            return item % 2 == 0;
        }
    });
// false
$.all(asList(1, 2, 3, 4),
    new Predicate<Integer>() {
        public Boolean apply(Integer item) {
            return item < 5;
        }
    });
// true

any $.any(collection, iterator)
Returns true if any of the values in the collection pass the iterator truth test. Short-circuits and stops traversing the collection if a true element is found.

$.any(asList(1, 2, 3, 4),
    new Predicate<Integer>() {
        public Boolean apply(Integer item) {
            return item % 2 == 0;
        }
    });
// true
$.any(asList(1, 2, 3, 4),
    new Predicate<Integer>() {
        public Boolean apply(Integer item) {
            return item == 5;
        }
    });
// false

include $.include(collection, value)
Returns true if the value is present in the collection.

$.include(asList(1, 2, 3), 3); // true

invoke $.invoke(collection, methodName, [arguments])
Calls the method named by methodName on each value in the collection. The arguments struct passed to invoke will be forwarded on to the method invocation.

$.invoke(asList(" foo", " bar "), "trim"); // ["foo", "bar"]

pluck $.pluck(collection, propertyName)
A convenient version of what is perhaps the most common use-case for map: extracting a collection of property values.

class Person {
    public final String name;
    public final Integer age;
    public Person(final String name, final Integer age) {
        this.name = name;
        this.age = age;
    }
};
$.pluck(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40)), "name");
// ["moe", "larry", "curly"]

max $.max(collection, [iterator])
Returns the maximum value in collection. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.

$.max(asList(10, 5, 100, 2, 1000));
// 100
$.max(asList(10, 5, 100, 2, 1000),
        new Function1<Integer, Integer>() {
    public Integer apply(Integer item) {
        return -item;
    }
});
// 2

min $.min(collection, [iterator])
Returns the minimum value in collection. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.

$.min(asList(10, 5, 100, 2, 1000));
// 2
$.min(asList(10, 5, 100, 2, 1000),
        new Function1<Integer, Integer>() {
    public Integer apply(Integer item) {
        return -item;
    }
});
// 1000

sortBy $.sortBy(collection, iterator)
Returns a sorted copy of collection, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the object key to sort by.

$.sortBy(asList(1, 2, 3, 4, 5, 6),
        new Function1<Integer, Integer>() {
        public Integer apply(Integer item) {
            return Double.valueOf(Math.sin(item) * 1000).intValue();
        }
    });
=> [5, 4, 6, 3, 1, 2]

groupBy $.groupBy(collection, iterator)
Splits a collection into sets, grouped by the result of running each value through iterator. If iterator is a string instead of a function, groups by the property named by iterator on each of the values.

$.groupBy(asList(1.3, 2.1, 2.4),
        new Function1<Double, Double>() {
        public Double apply(Double num) {
            return Math.floor(num);
        }
    });
=> {1.0=[1.3], 2.0=[2.1, 2.4]}

countBy $.countBy(collection, iterator)
Sorts a collection into groups and returns a count for the number of objects in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.

class Person {
    public final String name;
    public final Integer age;
    public Person(final String name, final Integer age) {
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return name + ", " + age;
    }
}
final Map<String, Integer> result =
$.countBy(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)),
    new Function1<Person, String>() {
    public String apply(Person person) {
        return person.name;
    }
});
=> {moe=2, curly=1}

sortedIndex $.sortedIndex(collection, value, [iterator])
Uses a binary search to determine the index at which the value should be inserted into the collection in order to maintain the collection's sorted order. If an iterator is passed, it will be used to compute the sort ranking of each value.

$.sortedIndex(asList(10, 20, 30, 40, 50), 35);
=> 3

shuffle $.shuffle(array)
Returns a shuffled copy of the array, using a version of the Fisher-Yates shuffle.

$.shuffle(asList(1, 2, 3, 4, 5, 6)
=> [4, 1, 6, 3, 5, 2]

sample $.sample(list, [n])
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.

$.sample(asList(1, 2, 3, 4, 5, 6)
=> 4 $.sample(asList(1, 2, 3, 4, 5, 6), 3)
=> [1, 6, 2]

toArray $.toArray(collection)
Converts the collection (object), into an array.

$.toArray(asList(1, 2, 3, 4));
=> [1, 2, 3, 4]

toMap $.toMap(collection)
Converts the collection to a map object.

$.toMap((new LinkedHashMap<String, String>() { {
        put("name1", "one");
        put("name2", "two");
    } }).entrySet());
=> {name1=one, name2=two}

size $.size(collection)
Return the number of values in the collection.

$.size(asList(1, 2, 3, 4));
=> 4

Array Functions

first $.first(array, [n])
Returns the first element of an array. Passing n will return the first n elements of the array.

$.first(asList(5, 4, 3, 2, 1));
=> 5

initial $.initial(array, [n])
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.

$.initial(asList(5, 4, 3, 2, 1));
=> [5, 4, 3, 2]

last $.last(array, [n])
Returns the last element of an array. Passing n will return the last n elements of the array.

$.last(asList(5, 4, 3, 2, 1));
=> 1

rest $.rest(array, [index])
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.

$.rest(asList(5, 4, 3, 2, 1));
=> [4, 3, 2, 1]

compact $.compact(array)
Returns a copy of the array with all falsy values removed. In Coldfusion, false, 0, and "" are all falsy.

$.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

flatten $.flatten(array, [shallow])
Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

$.flatten(asList(1, asList(2, asList(3, asList(asList(4))))));
=> [1, 2, 3, 4];
$.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), true); => [1, 2, [3, [[4]]]];

without $.without(array, [values])
Returns a copy of the array with all instances of the values removed.

$.without(asList(1, 2, 1, 0, 3, 1, 4), 0, 1)
=> [2, 3, 4]

union $.union(*arrays)
Computes the union of the passed-in arrays: the collection of unique items, in order, that are present in one or more of the arrays.

$.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1));
=> [1, 2, 3, 101, 10]

intersection $.intersection(*arrays)
Computes the collection of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

$.intersection(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1));
=> [1, 2]

difference $.difference(array, others)
Similar to without, but returns the values from array that are not present in the other arrays.

$.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10));
=> [1, 3, 4]

uniq $.uniq(array, [iterator])
Produces a duplicate-free version of the array. If you want to compute unique items based on a transformation, pass an iterator function.

$.uniq(asList(1, 2, 1, 3, 1, 4));
=> [1, 2, 3, 4]

zip $.zip(*arrays)
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

$.zip(asList("moe", "larry", "curly"), asList("30", "40", "50"), asList("true", "false", "false"));
=> [[moe, 30, true], [larry, 40, false], [curly, 50, false]]

object $.object(array, [values])
Converts an array into a struct. Pass either a single array of [key, value] pairs, or an array of keys, and an array of values.

$.object(asList("moe", "larry", "curly"), asList("30", "40", "50"));
=> [(moe, 30), (larry, 40), (curly, 50)]

indexOf $.indexOf(array, value)
Returns the index at which value can be found in the array, or -1 if value is not present in the array.

$.indexOf(asList(1, 2, 3), 2);
=> 1

lastIndexOf $.lastIndexOf(array, value)
Returns the index of the last occurrence of value in the array, or -1 if value is not present.

$.lastIndexOf(asList(1, 2, 3, 1, 2, 3), 2);
=> 4

range $.range([start], stop, [step])
A function to create flexibly-numbered arrays of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns an array of integers from start to stop, incremented (or decremented) by step, exclusive.

$.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
$.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
$.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
$.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
$.range(0);
=> []

concat $.concat(*arrays)
Concatenates any number of arrays together an returns the result.

$.concat(asList(1, 2), asList(3, 4))
=> [1, 2, 3, 4];

reverse $.reverse(array)
Returns a copy of the array in reverse order.

$.reverse(asList(1, 2, 3))
=> [3, 2, 1]

join $.join(array, [separator])
Returns a string with all array elements joined together. Default separator is a single space.

$.join(asList(1, 2), " and ");
=> "1 and 2"

slice $.slice(array, [from], [to])
Returns a subsection of the array. Negative values for to and from offset from the end of the array.

$.slice(asList(1, 2, 3, 4), 1);
=> [2, 3, 4]
$.slice(asList(1, 2, 3, 4), 3);
=> [3, 4]
$.slice(asList(1, 2, 3, 4), 2, -1);
=> [2, 3]
$.slice(asList(1, 2, 3, 4), -3, -1);
=> [2, 3]

Functions

bind $.bind(function, object, [*arguments])
Bind a function to a structure, meaning that whenever the function is called, the value of "this" will be the structure. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

class GreetingFunction implements Function1<String, String> {
    private final String name;
    public GreetingFunction(final String name) {
        this.name = name;
    }
    public String apply(final String greeting) {
        return greeting + ": " + this.name;
    }
}
$.bind(new GreetingFunction("moe")).apply("hi");
=> "hi: moe"

memoize $.memoize(function)
Memoizes a given function by caching the computed result. Useful for speeding up slow-running computations.

class FibonacciFuncion1 extends MemoizeFunction1<Integer> {
    public Integer calc(final Integer n) {
        return n < 2 ? n : apply(n - 1) + apply(n - 2);
    }
}
fibonacci = new FibonacciFuncion1().apply(10));
// 55

delay $.delay(function, wait, arguments)
Delays a function for the given number of milliseconds, and then calls it with the arguments supplied in the args struct.

$.delay(new Function<String>() {
    public String apply() {
        return "hi";
    }
}, 1000);
=> "hi" // appears after one second

once $.once(function)
Returns a function that will be executed at most one time, no matter how often you call it. Useful for lazy initialization.

final Integer[] counter = new Integer[] {0};
Function<Integer> incr = new Function<Integer>() { public Integer apply() {
    counter[0]++; return counter[0]; } };
Function<Integer> onceIncr = $.once(incr);
onceIncr.apply();
onceIncr.apply();
=> counter[0] == 1

debounce $.debounce(function, wait)
Returns a function that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds.

final Integer[] counter = new Integer[] {0};
Function<Void> incr = new Function<Void>() { public Void apply() { counter[0]++; return null; } };
Function<Void> debouncedIncr = $.debounce(incr, 50);
debouncedIncr.apply();
debouncedIncr.apply();
$.delay(debouncedIncr, 16);
$.delay(new Function<Void>() {
    public Void apply() {
        System.out.println(counter[0]);
        return null;
    }
}, 60);
Thread.sleep(120);
=> function argument is called only once

after $.after(count, function)
Returns a function that will only be executed after being called N times. When count <= 0, the result of calling the function immediately is returned.

final List<Integer> notes = asList(1, 2, 3);
final Function<Integer> renderNotes = $.after(notes.size(),
    new Function<Integer>() { public Integer apply() {
        return 4; } });
final List<Integer> result = new ArrayList<Integer>();
$.<Integer>each(notes, new Block<Integer>() {
    public void apply(Integer item) {
        result.add(item);
        Integer afterResult = renderNotes.apply();
        if (afterResult != null) {
            result.add(afterResult);
        }
    }
});
=> [1, 2, 3, 4]

before $.before(count, function)
Returns a function that will only be executed after being called N times. When count <= 0, the result of calling the function immediately is returned.

final List<Integer> notes = asList(1, 2, 3);
final Function<Integer> renderNotes = $.before(notes.size() - 1,
    new Function<Integer>() { public Integer apply() {
        return 4; } });
final List<Integer> result = new ArrayList<Integer>();
$.<Integer>each(notes, new Block<Integer>() {
    public void apply(Integer item) {
        result.add(item);
        Integer afterResult = renderNotes.apply();
        if (afterResult != null) {
            result.add(afterResult);
        }
    }
});
=> [1, 4, 2, 4, 3, 4]

wrap $.wrap(function, wrapper)
Returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function.

Function1<String, String> hello = new Function1<String, String>() {
    public String apply(final String name) {
        return "hello: " + name;
    }
};
Function1<Void, String> result = $.wrap(hello, new Function1<Function1<String, String>, String>() {
    public String apply(final Function1<String, String> func) {
        return "before, " + func.apply("moe") + ", after";
    }
});
result.apply(null);
=> "before, hello: moe, after"

compose $.compose(*functions)
Returns a function that is the composition of a list of functions, each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

Function1<String, String> greet = new Function1<String, String>() {
    public String apply(final String name) {
        return "hi: " + name;
    }
};
Function1<String, String> exclaim = new Function1<String, String>() {
    public String apply(final String statement) {
        return statement.toUpperCase() + "!";
    }
};
Function1<String, String> welcome = $.compose(greet, exclaim);
welcome.apply("moe");
=> 'hi: MOE!';

Object/Struct Functions

keys $.keys(object)
Retrieve all the names of the object's properties.

$.keys(new LinkedHashMap<String, Object>() { {
    put("one", 1); put("two", 2); put("three", 3); } });
=> ["one", "two", "three"]

values $.values(object)
Return all of the values of the object's own properties.

$.values(new LinkedHashMap<String, Integer>() { {
    put("one", 1); put("two", 2); put("three", 3); } });
=> [1, 2, 3]

pairs $.pairs(object)
Convert an object into a list of [key, value] pairs.

$.pairs(new LinkedHashMap() { {
    put("one", 1); put("two", 2); put("three", 3); } });
=> [(one, 1), (two, 2), (three, 3)]

invert $.invert(object)
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

$.invert(new LinkedHashMap<String, String>() { {
    put("Moe", "Moses"); put("Larry", "Louis"); put("Curly", "Jerome"); } });
=> [(Moses, Moe), (Louis, Larry), (Jerome, Curly)]

functions $.functions(object)
Returns a sorted array of the names of every method in an object -- that is to say, the name of every function property of the object.

$.functions($.class);
=> ["all", "any", "bind", "clone", "compact", "compose" ...

extend $.extend(destination, *sources)
Copy all of the properties in the source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.

$.extend(new LinkedHashMap<String, Object>() { { put("name", "moe"); } },
    new LinkedHashMap<String, Object>() { { put("age", 50); } });
=> {name=moe, age=50}

pick $.pick(object, *keys)
Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys).

$.pick(
    new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 50); put("userid", "moe1"); } },
    "name", "age"
);
=> [(name, moe), (age, 50)]

omit $.omit(object, *keys)
Return a copy of the object, filtered to omit the blacklisted keys (or array of keys).

$.omit(
    new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 50); put("userid", "moe1"); } },
    "userid"
);
=> [(name, moe), (age, 50)]

defaults $.defaults(object, *defaults)
Fill in missing properties in object with default values from the defaults objects, and return the object. As soon as the property is filled, further defaults will have no effect.

Map<String, String> iceCream = new LinkedHashMap<String, String>() { { put("flavor", "chocolate"); } };
Map<String, String> result = $.defaults(iceCream, new LinkedHashMap<String, String>() { {
    put("flavor", "vanilla"); put("sprinkles", "lots"); } });
=> {flavor=chocolate, sprinkles=lots}

clone $.clone(object)
Create a shallow-copied clone of the object. Any nested structs or objects will be copied by reference, not duplicated.

$.clone(new LinkedHashMap<String, String>() { {
    put("name", "moe"); } });
=> {name=moe}

has $.has(object, key)
Does the object contain the given key?

$.has(new LinkedHashMap<String, Integer>() { {
    put("a", 1); put("b", 2); put("c", 3); } }, "b");
=> true

isEqual $.isEqual(object, other)
Performs a deep comparison between the two objects, to determine if they should be considered equal.

Map<String, Object> stooge = new LinkedHashMap<String, Object>() { {
    put("name", "moe"); put("luckyNumbers", asList(13, 27, 34)); } };
Map<String, Object> clone = new LinkedHashMap<String, Object>() { {
    put("name", "moe"); put("luckyNumbers", asList(13, 27, 34)); } };
=> stooge == clone // false
=> $.isEqual(stooge, clone); // true

isEmpty $.isEmpty(object)
Returns true if object contains no values.

$.isEmpty(asList(1, 2, 3, 4))
=> false
$.isEmpty(new ArrayList<String>())
=> true

isArray $.isArray(object)
Returns true if object is an Array.

$.isArray("string")
=> false
$.isArray(new int[] {1, 2, 3, 4, 5});
=> true

isObject $.isObject(object)
Returns true if value is an Object.

$.isObject(new LinkedHashMap<String, String>())
=> true
$.isObject(null);
=> false

isFunction $.isFunction(object)
Returns true if object is a Function.

$.isFunction(new Function1<String, Integer>() {
    public Integer apply(final String arg) { return null; } })
=> true

isString $.isString(object)
Returns true if object is a String. Uses Java String type comparison.

$.isString("moe");
=> true
$.isString(1);
=> false

isNumber $.isNumber(object)
Returns true if object is of a Java numeric type.

$.isNumber(1);
=> true

isBoolean $.isBoolean(object)
Returns true if object is a boolean.

$.isBoolean(false);
=> true

isDate $.isDate(object)
Returns true if object is a date.

$.isDate(new java.util.Date())
=> true

Utility Functions

times $.times(n, iterator)
Invokes the given iterator function n times.

final List<Integer> result = new ArrayList<Integer>();
$.times(3, new Function<Integer>() {
    public Integer apply() {
        result.add(1);
        return null;
    }
});
=> [1, 1, 1]

random $.random([min], max)
Returns a random integer between min and max, inclusive. If you only pass one argument, it will return a number between 0 and that number.

$.random(0, 100);
=> 42

mixin $.mixin(object)
Allows you to extend Underscore with your own utility functions.

$.mixin("capitalize", new Function1<String, String>() {
    public String apply(final String string) {
        return String.valueOf(string.charAt(0)).toUpperCase() + string.substring(1).toLowerCase();
    }
});
new $("fabio").call("capitalize").get()
=> "Fabio"

uniqueId $.uniqueId(prefix)
Generates an identifier that is unique for this instance of Underscore

$.uniqueId("c");
=> c1

uniquePassword $.uniquePassword()
Generates a random text with 8-15 characters length

$.uniquePassword();
=> FKV276qgb-&

escape $.escape(input)
Escapes a string for insertion into HTML, replacing &, <, >, and " characters.

$.escape("Curly, Larry & Moe");
=> "Curly, Larry &amp; Moe"

result $.result(object, property)
If the value of the named property is a function then invoke it; otherwise, return it.

Map<String, Object> object = new LinkedHashMap<String, Object>() { {
    put("cheese", "crumpets");
    put("stuff", new Function<String>() { public String apply() { return "nonsense"; } });
} };

$.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() {
    public Boolean apply(Map.Entry<String, Object> item) {
        return item.getKey().equals("cheese");
    }
});
=> "crumpets"
$.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() { public Boolean apply(Map.Entry<String, Object> item) { return item.getKey().equals("stuff"); } }); => "nonsense"

times $.times(n, iterator)
Invokes the given iterator function n times.

final List<Integer> result = new ArrayList<Integer>();
$.times(3, new Function<Integer>() {
    public Integer apply() {
        result.add(1);
        return null;
    }
});
=> [1, 1, 1]

Chaining

You can use Underscore-java in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers.

$.map(asList(1, 2, 3), new Function1<Integer, Integer>() {
    public Integer apply(Integer item) {
        return item * 2;
    }
});
new $(asList(1, 2, 3)).map(new Function1<Integer, Integer>() {
    public Integer apply(Integer item) {
        return item * 2;
    }
});

Calling chain will cause all future method calls to return wrapped objects. When you've finished the computation, call item or value to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

final List<Map<String, Object>> lyrics = new ArrayList<Map<String, Object>>() { {
    add(new LinkedHashMap<String, Object>() { {
        put("line", 1); put("words", "I'm a lumberjack and I'm okay"); } });
    add(new LinkedHashMap<String, Object>() { {
        put("line", 2); put("words", "I sleep all night and I work all day"); } });
    add(new LinkedHashMap<String, Object>() { {
        put("line", 3); put("words", "He's a lumberjack and he's okay"); } });
    add(new LinkedHashMap<String, Object>() { {
        put("line", 4); put("words", "He sleeps all night and he works all day"); } });
} };
final String result = $.chain(lyrics)
    .map(
        new Function1<Map<String, Object>, List<String>>() {
        public List<String> apply(Map<String, Object> item) {
            return asList(String.valueOf(item.get("words")).split(" "));
        }
    })
    .flatten()
    .reduce(
        new FunctionAccum<Map<String, Integer>, String>() {
        public Map<String, Integer> apply(Map<String, Integer> accum, String item) {
            if (accum.get(item) == null) {
                accum.put(item, 1);
            } else {
                accum.put(item, accum.get(item) + 1);
            }
            return accum;
        }
    },
    new LinkedHashMap<String, Integer>()
    )
    .item();

=> {lumberjack: 2, all: 4, night: 2 ... }

chain$.chain(obj)
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until item or value is called.

final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { {
    add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } });
    add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } });
    add(new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } });
} };
final String youngest = $.chain(stooges)
    .sortBy(
        new Function1<Map<String, Object>, Integer>() {
        public Integer apply(Map<String, Object> item) {
            return (Integer) item.get("age");
        }
    })
    .map(
        new Function1<Map<String, Object>, String>() {
        public String apply(Map<String, Object> item) {
            return item.get("name") + " is " + item.get("age");
        }
    })
    .first().item();

=> "moe is 21"

value$.chain(obj).value()
Extracts the value of a wrapped object.

$.chain(Arrays.asList(1, 2, 3)).value();
=> [1, 2, 3]

Change Log

1.23 -- Feb 2nd, 2017

1.22 -- Jan 2nd, 2017

1.21 -- Dec 1st, 2016

1.20 -- Nov 1st, 2016

1.19 -- Oct 1st, 2016

1.18 -- Sep 1st, 2016

1.17 -- Aug 1st, 2016

1.16 -- Jul 1st, 2016

1.15 -- Jun 1st, 2016

1.14 -- May 1st, 2016

1.13 -- Apr 1st, 2016

1.12 -- Mar 1st, 2016

1.11 -- Feb 4th, 2016

1.10 -- Jan 1st, 2016

1.9 -- Dec 1st, 2015

1.8 -- Nov 1st, 2015

1.7 -- Oct 1st, 2015

1.6 -- Sep 1st, 2015

1.5 -- Aug 1st, 2015

1.4 -- July 1st, 2015

1.3 -- June 1st, 2015

1.2 -- May 1st, 2015

1.1 -- April 4th, 2015

1.0 -- December 27, 2014

Fork me on GitHub