Constructing collections from existing data
suggest changeStandard Collections
Java Collections framework
A simple way to construct a List from individual data values is the java.util.Arrays method Arrays.asList. The result is a fixed-size list backed by the array:
List<String> data = Arrays.asList("ab", "bc", "cd", "ab", "bc", "cd");
The common general-purpose collection implementations provide constructors that take another collection and add all of its elements at construction time:
List<String> list = new ArrayList<>(data); // will add data as is
Set<String> set1 = new HashSet<>(data); // will add data keeping only unique values
SortedSet<String> set2 = new TreeSet<>(data); // will add data keeping unique values and sorting
Set<String> set3 = new LinkedHashSet<>(data); // will add data keeping only unique values and preserving the original order
Google Guava Collections framework
Google Guava provides utility classes with static methods for constructing Lists and Sets:
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
List<String> list1 = Lists.newArrayList("ab", "bc", "cd");
List<String> list2 = Lists.newArrayList(data);
Set<String> set4 = Sets.newHashSet(data);
SortedSet<String> set5 = Sets.newTreeSet(Arrays.asList("bc", "cd", "ab", "bc", "cd"));
Sets.newTreeSet takes an Iterable, a Comparator, or no arguments. It has no varargs overload.
Mapping Collections
Java Collections framework
Similarly for maps, given a Map<String, Object> map a new map can be constructed with all elements as follows:
Map<String, Object> map1 = new HashMap<>(map);
SortedMap<String, Object> map2 = new TreeMap<>(map);
Apache Commons Collections framework
Apache Commons Lang can build a Map from an array with ArrayUtils.toMap:
import org.apache.commons.lang3.ArrayUtils;
// Create a Map mapping colors.
Map<Object, Object> colorMap = ArrayUtils.toMap(new String[][] {
{"RED", "#FF0000"},
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
});
Each element of the array must be either a Map.Entry or an Array, containing at least two elements, where the first element is used as key and the second as value.
Google Guava Collections framework
Google Guava’s utility class for maps is Maps:
import com.google.common.collect.Maps;
void howToCreateMapsMethod(Function<? super K, V> valueFunction,
Iterable<K> keys1,
Set<K> keys2,
SortedSet<K> keys3) {
ImmutableMap<K, V> map1 = Maps.toMap(keys1, valueFunction); // immutable copy
Map<K, V> map2 = Maps.asMap(keys2, valueFunction); // live view
SortedMap<K, V> map3 = Maps.asMap(keys3, valueFunction); // live sorted view
}
Maps.toMap always returns an immutable copy. The live view, including the sorted one, is Maps.asMap.
Using Stream,
Stream.of("xyz", "abc").collect(Collectors.toList());
or
Arrays.stream(new String[] {"xyz", "abc"}).collect(Collectors.toList());