Useful Java snippets

Starting this post to keep track of some useful Java snippets I use/come across.

Singleton Map/List

Need a map, but with just one object in it? Don’t feel like going through all this boilerplate just to get that?

Map<KeyType, ValueType> myMap = new HashMap<KeyType, ValueType>();
myMap.put(key, value);

Collections.singletonMap to the rescue.

With one fell swoop, you’ve got yourself an immutable map:

Collections.singletonMap(key, value);

In the same vein, there’s also a Collections.singletonList method for when you need a list with a single item.

Generate a random String of a certain length

(Thanks to this StackOverflow post)

Import org.apache.commons.text.RandomStringGenerator, and use it like this:

RandomStringGenerator randomStringGenerator =
        new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)

Comma-separate a Collection of Strings with a StringJoiner

Say you have this List of Strings: ["Alice", "Bob", "Carol"], and you want to concatenate them into one String that’s comma-separated. Simply use a StringJoiner.

String commaSeparatedNames =
     .collect(Collectors.joining(", "));

Reference: Class StringJoiner

Convert between time units

You can use Java’s TimeUnit class to easily convert between time units. For example, convert 15 seconds to milliseconds with:


Catch multiple exceptions

Java 7 syntax lets you catch multiple exceptions at once:

catch(RuntimeException | IOException | SQLException e)

Reference: Java Catch Multiple Exceptions, Rethrow Exception