Starting this post to keep track of some useful Java snippets I use/come across.
Need a map, but with just one object in it? Don’t feel like going through all this boilerplate just to get that?
Collections.singletonMap to the rescue.
With one fell swoop, you’ve got yourself an immutable map:
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)
org.apache.commons.text.RandomStringGenerator, and use it like this:
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 = names.stream() .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)