Reputation: 77
I have an ArrayList list
with the values 90, 80, 75
in it that I want to convert to an IntStream.
I have tried using the function list.stream()
, but the issue I come upon is that when I attempt to use a lambda such as:
list.stream().filter(x -> x >= 90).forEach(System.out.println(x);
It will not let me perform the operations because it is a regular stream, not an IntStream. Basically what this line is supposed to do is that if the 90 is in the list to print it out.
What am I missing here? I can't figure out how to convert the Stream to an IntStream.
Upvotes: 0
Views: 3610
Reputation: 298153
You can convert the stream to an IntStream
using .mapToInt(Integer::intValue)
, but only if the stream has the type Stream<Integer>
, which implies that your source list is a List<Integer>
.
In that case, there is no reason why
list.stream().filter(x -> x >= 90).forEach(System.out::println);
shouldn’t work. It’s even unlikely that using an IntStream
improves the performance for this specific task.
The reason why you original code doesn’t work, is that .forEach(System.out.println(x);
isn’t syntactically correct. First, there is a missing closing brace. Second, System.out.println(x)
is neither, a lambda expression nor a method reference. You have to use either,
.forEach(x -> System.out.println(x));
or .forEach(System.out::println);
. In other words, the error is not connected to the fact that this is a generic Stream
instead of an IntStream
.
Upvotes: 1
Reputation: 1704
Use mapToInt
as
list.stream()
.mapToInt(Integer::intValue)
.filter(x -> x >= 90)
.forEach(System.out::println);
Upvotes: 5