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.
- 3,182
- 7
- 28
- 38
- 77
- 1
- 6
-
Maybe .map()? (I don't use streams often, so...) – markspace Mar 22 '18 at 01:46
-
How is your `ArrayList` declared? – tinstaafl Mar 22 '18 at 01:47
-
First example in the streams documentation uses `mapToInt` https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html – markspace Mar 22 '18 at 01:47
-
@tinstaafl ArrayList
list = new ArrayList – dwagner6 Mar 22 '18 at 01:52(); -
Pertaining to the title, might just be little simpler - [`list.stream().flatMapToInt(IntStream::of)`](https://stackoverflow.com/a/53878820/1746118) – Naman Dec 21 '18 at 03:43
2 Answers
Use mapToInt as
list.stream()
.mapToInt(Integer::intValue)
.filter(x -> x >= 90)
.forEach(System.out::println);
- 1,654
- 1
- 14
- 21
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.
- 285,553
- 42
- 434
- 765