My latest Java project is IJDK, which brings many Rubyisms into the world of Java, mainly by extending or wrapping core JDK classes with behavior more familiar to Ruby programmers, but, in my experience, invaluable as a Java programmer as well.

Array

The class that I’ve been using more than any other is Array, which is a subclass of java.util.ArrayList, so it can be used consistently wherever an ArrayList (or List or Collection) is expected.

For example, the get method from ArrayList is overridden, so negative indices can be used. That is, -1 is the last element in the array, -2 is the second to last one, and so on. Unlike ArrayList, doing a get with an element out of range does not throw ArrayIndexOutOfBoundsException, but instead returns null.

A sample:

    Array<String> simpsons = Array.of("homer", "marge", "lisa", "bart");

    simpsons.append("grandpa").append("maggie");

    if (simpsons.containsAny("ned", "maude")) {
    }

    String homer = simpsons.get(0);
    String maggie = simpsons.get(-1);
    String bart = simpsons.get(-3);
    String noone = simpsons.get(20);
    Array<String> adults = simpsons.elements(0, 1, -2);
    Array<String> kids = simpsons.elements(2, 3, -1).plus(Array.of("nelson", "milhouse"));
    
    Array<String> sorted = simpsons.sorted();
    Array<String> unique = simpsons.unique();
    Array<String> nonNull = simpsons.compact();

    String str = sorted.get(0, -2).join(", ") + " and " + sorted.get(-1);
    // => bart, grandpa, homer, lisa, maggie and marge

That class is more thoroughly explained here, and has its Javadoc here.

Str

The runner-up in terms of usage is Str, a wrapper around the java.lang.String class. It differs from String in a few ways, one that the referenced string can be null, and any deferences from Str will return a null object instead of throwing a null pointer exception.

    Str str = Str.of("This Is a Test");

    Character c;

    c = str.get(0);
    c = str.get(-1);
    c = str.get(-2);

    String s;

    s = str.left(4);

    s = str.right(3);

    Str text = Str.of("abc\ndef\n\n");
    s = text.chomp();

    s = text.chompAll();

    String[] lines = text.split("\n");

    List<String> chunks = Str.of("abc def\nghi\tjkl").toList();

    boolean b;

    b = str.startsWith("T");

    b = str.endsWith("t");

There is more in development, of course, with a major overhaul in process of Str.

That being said, I think we should immediately deprecate any string concatenation that combines ‘19’ with ‘99’. – Larry Wall

Related