How can I convert an array of primitive int, long, or double values into a collection of type Map?
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> collect(int[] values) {
return // Collect the array of values into a Map<Integer, String>
}
public static void main(String[] args) {
Map<Integer, String> map = collect(numbers);
System.out.println(map);
// {0=zero, 3=three, 5=five, 6=six, 7=seven, 8=eight, 9=nine}
}
}
In order to convert an array of primitive values to a collection; the values need to either be
boxedinto corresponding object types, or thecollectmethod for the primitive stream needs to be called.Boxing
Here are the 8 primitive types and their corresponding wrapper classes:
bool→Booleanbyte→Bytechar→Characterdouble→Doublefloat→Floatint→Integerlong→Longshort→ShortIn the code below, the
int[]is transformed into anIntStreamwhich is then boxed into aStream<Integer>and collected with theCollectors.toMapcollector.Primitive streams
The
Arrays.streammethod has been overridden to accept only arrays ofdouble,int, andlong.double[]→DoubleStreamint[]→IntStreamlong[]→LongStreamIn the code below, the
collectmethod is called directly on the primitive stream object. It takes three arguments:supplier- in this case aHashMap<Integer, String>accumulator- how to apply the iteree to the suppliercombiner- how multiple values are combined