Master Java Collection Conversions with 10 Stream Utility Methods
This article presents a set of ten Java Stream‑based utility methods that simplify converting between Collection, List, Set, and Map types, showing practical examples, test cases, and reusable implementations for common data‑mapping scenarios.
Purpose
A small utility class wraps Java Stream operations to provide concise, reusable conversions between Collection, List, Set, and Map for objects such as OrderItem.
Supported conversion scenarios
Convert Collection<OrderItem> to List<OrderItem> Convert Collection<OrderItem> to Set<OrderItem> Convert List<OrderItem> to List<Long> (extracting IDs)
Convert Set<OrderItem> to Set<Long> Convert Collection<OrderItem> to List<Long> Convert Collection<OrderItem> to Set<Long> Build Map<K, OrderItem> from a collection by extracting a key
Build Map<K, V> from a collection by extracting a key and transforming the value
Transform the values of Map<Long, OrderItem> to
Map<Long, Double>Collection → List / Set
public static <T> List<T> toList(Collection<T> collection) {
if (collection == null) {
return new ArrayList<>();
}
if (collection instanceof List) {
return (List<T>) collection;
}
return collection.stream().collect(Collectors.toList());
}
public static <T> Set<T> toSet(Collection<T> collection) {
if (collection == null) {
return new HashSet<>();
}
if (collection instanceof Set) {
return (Set<T>) collection;
}
return collection.stream().collect(Collectors.toSet());
}Example
@Test
public void testToList() {
Collection<OrderItem> coll = ...;
List<OrderItem> list = toList(coll);
}
@Test
public void testToSet() {
Collection<OrderItem> coll = ...;
Set<OrderItem> set = toSet(coll);
}Collection → Map
Two overloaded toMap methods handle key extraction and optional value conversion. A merge function resolves duplicate keys.
public static <T, K> Map<K, T> toMap(Collection<T> collection,
Function<? super T, ? extends K> keyMapper) {
return toMap(collection, keyMapper, Function.identity());
}
public static <T, K, V> Map<K, V> toMap(Collection<T> collection,
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction) {
return toMap(collection, keyFunction, valueFunction, pickSecond());
}
public static <T, K, V> Map<K, V> toMap(Collection<T> collection,
Function<? super T, ? extends K> keyFunction,
Function<? super T, ? extends V> valueFunction,
BinaryOperator<V> mergeFunction) {
if (CollectionUtils.isEmpty(collection)) {
return new HashMap<>(0);
}
return collection.stream()
.collect(Collectors.toMap(keyFunction, valueFunction, mergeFunction));
}
public static <T> BinaryOperator<T> pickFirst() { return (k1, k2) -> k1; }
public static <T> BinaryOperator<T> pickSecond() { return (k1, k2) -> k2; }Example
@Test
public void testToMap() {
Collection<OrderItem> coll = ...;
Set<OrderItem> set = toSet(coll);
Map<Long, OrderItem> map = toMap(set, OrderItem::getOrderId);
}
@Test
public void testToMapWithValue() {
Collection<OrderItem> coll = ...;
Set<OrderItem> set = toSet(coll);
Map<Long, Double> priceMap = toMap(set, OrderItem::getOrderId, OrderItem::getActPrice);
}Map value conversion
Convert the values of an existing map while keeping the original keys. The method accepts a BiFunction that receives both key and value, and a merge function for duplicate keys.
public static <K, V, C> Map<K, C> convertMapValue(Map<K, V> map,
BiFunction<K, V, C> valueFunction,
BinaryOperator<C> mergeFunction) {
if (isEmpty(map)) {
return new HashMap<>();
}
return map.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(),
e -> valueFunction.apply(e.getKey(), e.getValue()),
mergeFunction));
}
public static <K, V, C> Map<K, C> convertValue(Map<K, V> originMap,
BiFunction<K, V, C> valueConverter) {
return convertMapValue(originMap, valueConverter, pickSecond());
}Example
@Test
public void testConvertValue() {
Collection<OrderItem> coll = ...;
Set<OrderItem> set = toSet(coll);
Map<Long, OrderItem> map = toMap(set, OrderItem::getOrderId);
Map<Long, Double> priceMap = convertMapValue(map, (id, item) -> item.getActPrice());
Map<Long, String> tokenMap = convertMapValue(map, (id, item) -> id + item.getName());
}Element‑wise mapping to another type
Generic helpers map a List or Set of any element type to a List or Set of another type using a Function. Additional overloads accept a generic Collection as source.
public static <T, R> List<R> map(List<T> source, Function<T, R> mapper) {
return source.stream().map(mapper).collect(Collectors.toList());
}
public static <T, R> Set<R> map(Set<T> source, Function<T, R> mapper) {
return source.stream().map(mapper).collect(Collectors.toSet());
}
public static <T, R> List<R> mapToList(Collection<T> source, Function<T, R> mapper) {
return source.stream().map(mapper).collect(Collectors.toList());
}
public static <T, R> Set<R> mapToSet(Collection<T> source, Function<T, R> mapper) {
return source.stream().map(mapper).collect(Collectors.toSet());
}Example
@Test
public void testMapToList() {
Collection<OrderItem> coll = ...;
List<Long> ids = mapToList(coll, OrderItem::getOrderId);
}
@Test
public void testMapToSet() {
Collection<OrderItem> coll = ...;
Set<Long> ids = mapToSet(coll, OrderItem::getOrderId);
}Summary of conversions
Collection → List / Set of the same element type
List / Set → List / Set of a different element type (e.g., extracting IDs)
Collection → Map with key extracted from each element
Collection → Map with both key extraction and value transformation
Map value conversion using a
BiFunctionSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
