How do I convert a Java 8 IntStream to a List?
IntStream::boxed
IntStream::boxed
turns an IntStream
into a Stream<Integer>
, which you can then collect
into a List
:
theIntStream.boxed().collect(Collectors.toList())
The boxed
method converts the int
primitive values of an IntStream
into a stream of Integer
objects. The word "boxing" names the int
⬌ Integer
conversion process. See Oracle Tutorial.
Java 16 and later
Java 16 brought the shorter toList
method. Produces an unmodifiable list. Discussed here.
theIntStream.boxed().toList()
How to convert IntStream to List in java?
Explanation
Random#ints
returns IntStream
, not a Stream<Integer>
, that is the problem.
IntStream
is a special class to represent primitive int
s. But generics in Java do not support primitives, i.e. there is no List<int>
. So you first have to make your int
s Integer
s, the wrapper class. Then you can collect to List<Integer>
.
Solution
Just box it and it works.
stream.boxed().toList() // since Java 16
// or
stream.boxed().collect(Collectors.toList())
Also see the documentation of IntStream#boxed
:
Returns a Stream consisting of the elements of this stream, each boxed to an Integer.
For understanding, boxed()
is roughly equivalent to
stream.mapToObj(x -> Integer.valueOf(x))
So in your case:
public static void main(String[] args) {
System.out.println(
new Random()
.ints(10, 0, 20)
.boxed()
.toList());
}
How to convert IntStream into List Character ?
You may map each int
to a char
then collect into a list, this will result in a list of character given by their ASCII code
List<Character> r = IntStream.range(50, 80).mapToObj(a -> (char) a).collect(Collectors.toList());
System.out.println(r); // [2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, @, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
Cannot collect Random int stream into a List collection
Before you can collect an IntStream
to a List<Integer>
, you need to call IntStream#boxed
to transform it into a Stream<Integer>
:
IntStream randIntStream = new Random().ints(1000);
List<Integer> randomInts = randIntStream.boxed()
.collect(Collectors.toCollection(ArrayList::new));
Cannot convert IntStream to some Object Stream
The IntStream
class's map
method maps int
s to more int
s, with a IntUnaryOperator
(int
to int
), not to objects.
Generally, all streams' map
method maps the type of the stream to itself, and mapToXyz
maps to a different type.
Try the mapToObj
method instead, which takes an IntFunction
(int
to object) instead.
.mapToObj(id -> new MyObject(id));
How to populate List Integer from IntStream?
In the second example nextInt()
from the Random
class returns a primitive int
, which can't be collected to a List
. Add a call to boxed
, which will convert the int
's to their wrapper class Integer
:
public static List<Integer> populateListStream2(int numberOfElements){
return IntStream.range(0,numberOfElements)
.map(e -> random.nextInt(numberOfElements/10))
.boxed()
.collect(Collectors.toList());
}
But the first one also returned a primitive int through casting!
Yes, but it was in a Stream
, so it was autoboxed to an Integer
. You can tell by running:
Stream.generate(new Random()::nextDouble)
.limit(numberOfElements)
.map(e -> (int)(e*numberOfElements/10))
.peek(e -> System.out.println(e.getClass()))
.collect(Collectors.toList());
Which prints:
class java.lang.Integer
The latter was an IntStream
. One of IntStream
's benefits is to avoid auto boxing and unboxing. It won't box unless you explicitly call boxed()
Also note that there are methods from the Random
class that already return a Stream
of random numbers such as ints()
and doubles()
Java8 stream - how to get convert Set to List when .map() found a Set
Use flatMap
:
List<Task> taskList = projectMap.stream()
.flatMap(p -> p.getProject().getTasks().stream())
.collect(Collector.toList());
How do I filter a stream of integers into a list?
IntStream
doesn't contain a collect
method that accepts a single argument of type Collector
. Stream
does. Therefore you have to convert your IntStream
to a Stream
of objects.
You can either box the IntStream
into a Stream<Integer>
or use mapToObj
to achieve the same.
For example:
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
boxed()
will return a Stream consisting of the elements of this stream, each boxed to an Integer.
or
return IntStream.range(0, 10)
.filter(i -> compare(z, f(i)))
.mapToObj(Integer::valueOf)
.collect(Collectors.toCollection(ArrayList::new));
Java stream - map and store array of int into Set
It looks like arr1
is an int[]
and therefore, Arrays.stream(arr1)
returns an IntStream
. You can't apply .collect(Collectors.toSet())
on an IntStream
.
You can box it to a Stream<Integer>
:
Set<Integer> mySet = Arrays.stream(arr1)
.boxed()
.map(ele -> ele - 2)
.collect(Collectors.toSet());
or even simpler:
Set<Integer> mySet = Arrays.stream(arr1)
.mapToObj(ele -> ele - 2)
.collect(Collectors.toSet());
How to convert a list of objects containing other objects into HashMap
As you suspected, groupingBy
is the right approach.
fruitFlowers.stream().collect(Collectors.groupingBy(
i -> i.fruit,
Collectors.mapping(i -> i.flower, Collectors.toList())
));
The first parameter to groupingBy
defines how you want to group them. In this case, we want to group by fruits.
The second parameter describes what the value of the resulting map should be. In this case, we want the values to be the list of flowers.
Note that this approach only works if groupingBy
can deduce that two fruits are equivalent. This requires that the Fruit
class contains an appropriate implementation of equals
and hashCode
.
If the Fruit
class cannot be extended to add those methods, one can change the first lambda to i -> i.fruit.name
, but that would make the resulting Map
to have String
keys instead of Fruit
.
Related Topics
What Does Statement.Setfetchsize(Nsize) Method Really Do in SQL Server Jdbc Driver
Generate All Combinations from Multiple Lists
Parsing an Arithmetic Expression and Building a Tree from It in Java
Java Count Occurrence of Each Item in an Array
Cannot Issue Data Manipulation Statements with Executequery()
Reusing a Preparedstatement Multiple Times
How to Switch JPAnels Inside a Jframe
Java Heap Terminology: Young, Old and Permanent Generations
Nullpointerexception in Java with No Stacktrace
Difference Between _Java_Options, Java_Tool_Options and Java_Opts
Integrating Tomcat and Eclipse as a Hot-Deploy Environment
How to Parse Output of New Date().Tostring()
Java Datetimeformatterbuilder Fails on Testtime
Android "Gps Requires Access_Fine_Location" Error, Even Though My Manifest File Contains This
How to Call JavaScript from Android
Garbage Collector Log (Loggc) File Rotation with Logrotate Does Not Work Properly