0

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.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
dwagner6
  • 77
  • 1
  • 6

2 Answers2

5

Use mapToInt as

list.stream()
    .mapToInt(Integer::intValue)
    .filter(x -> x >= 90)
    .forEach(System.out::println);
John
  • 1,654
  • 1
  • 14
  • 21
1

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.

Holger
  • 285,553
  • 42
  • 434
  • 765