Java Collections Quick Reference

A cheat sheet for my frequently used/forgotten Java Collections snippets.

Quickly Create a List

import static java.util.Arrays.asList;
asList("hello", "goodbye");
import static java.util.Collections.unmodifiableList;
unmodifiableList(asList("hello", "goodbye"));

Empty Collection Syntax

List<String> requiredInputs = Collections.<String>emptyList();

Also see here.

Safe Empty Array

public static String[] safe(String[] other ) {
    return other == null ? new String[0] : other;
}

Convert Array to List

Arrays.asList(values)

Collection to Array

values.toArray(new String[values.size()])

Loop Over Keys And Values In A Map

for (Iterator<Map.Entry<String, Object>> it = resultsData.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(String.format("key: %s, value: %s", key, value));
        }