A cheat sheet for my frequently used/forgotten Java Collections snippets.
Quickly Create a List
1 2 3 4 |
import static java.util.Arrays.asList; asList("hello", "goodbye"); import static java.util.Collections.unmodifiableList; unmodifiableList(asList("hello", "goodbye")); |
Empty Collection Syntax
1 |
List<String> requiredInputs = Collections.<String>emptyList(); |
Also see here.
Safe Empty Array
1 2 3 |
public static String[] safe(String[] other ) { return other == null ? new String[0] : other; } |
Convert Array to List
1 |
Arrays.asList(values) |
Collection to Array
1 |
values.toArray(new String[values.size()]) |
Loop Over Keys And Values In A Map
1 2 3 4 5 6 |
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)); } |