In order to convert an array of primitive values to a collection; the values need to either be boxed
into corresponding object types, or the collect
method for the primitive stream needs to be called.
Boxing
Here are the 8 primitive types and their corresponding wrapper classes:
bool
→ Boolean
byte
→ Byte
char
→ Character
double
→ Double
float
→ Float
int
→ Integer
long
→ Long
short
→ Short
See also: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
In the code below, the int[]
is transformed into an IntStream
which is then boxed into a Stream<Integer>
and collected with the Collectors.toMap
collector.
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class PrimitiveStreamCollection {
private static final String[] words = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};
private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 };
public static Map<Integer, String> collectBoxed(int[] values) {
return Arrays.stream(values)
.boxed()
.collect(
Collectors.toMap(
Function.identity(),
value -> words[value]));
}
public static void main(String[] args) {
Map<Integer, String> boxedMap = collectBoxed(numbers);
System.out.println(boxedMap);
}
}
Primitive streams
The Arrays.stream
method has been overridden to accept only arrays of double
, int
, and long
.
double[]
→ DoubleStream
int[]
→ IntStream
long[]
→ LongStream
In the code below, the collect
method is called directly on the primitive stream object. It takes three arguments:
supplier
- in this case a HashMap<Integer, String>
accumulator
- how to apply the iteree to the supplier
combiner
- how multiple values are combined
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class PrimitiveStreamCollection {
private static final String[] words = {
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};
private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 };
public static Map<Integer, String> collectUnboxed(int[] values) {
return Arrays.stream(values)
.collect(
HashMap::new,
(acc, value) -> acc.put(value, words[value]),
HashMap::putAll);
}
public static void main(String[] args) {
Map<Integer, String> unboxedMap = collectUnboxed(numbers);
System.out.println(unboxedMap);
}
}