0

I tried:

Stream stream = Pattern.compile(" ").splitAsStream(sc.nextLine()); stream.forEach(item) -> {}); 

and got:

Compilation Error... File.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details. 

so I tried:

Stream stream = Pattern.compile(" ").splitAsStream(sc.nextLine()); stream.forEach((String item) -> {}); 

and got:

Compilation Error... 15: error: incompatible types: incompatible parameter types in lambda expression stream.forEach((String item) -> {}); ^ Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error 

How can I make this .forEach() pass compilation?

1 Answer 1

6

You've defined your Stream as a raw type, which removes all type information and (basically) uses Object as the type.

Try this:

Stream<String> stream = Pattern.compile(" ").splitAsStream(sc.nextLine()); // ^----^ add a generic type to the declaration stream.forEach(item -> { // item is know to be a String }); 

Or easier, just in-line it:

Pattern.compile(" ").splitAsStream(sc.nextLine()).forEach(item -> {}); 

Or easier still:

Arrays.stream(sc.nextLine().split(" ")).forEach(item -> {}); 

Although simpler, the last version uses O(n) space because the entire input is split before the first forEach() is executed.
The other versions use O(1) space because the Pattern#splitAsStream() uses a Matcher internally to iterate through the input thus consumes the input match at a time.
Unless the input is quite large, this side effect won't make much difference.

Sign up to request clarification or add additional context in comments.

6 Comments

many thanks, why does inlining matters? it looks to me just shortening the number of lines or chars of code, how come it actually effects the compilation or not of the code??
@Jas: there is no performance improvement, if you are thinking into that direction. But chaining all Stream operations makes it impossible to have such declaration errors like in your question. Also, having no variables pointing to the Stream, ensures that you don’t try to use the Stream twice.
but what is the reason inlining it fixed the type problem? i never had a case where multiline vs single line has a different type issue
but what is the reason inlining it fixed the type problem? why is there a difference between assigning the result into a Stream and using it versus using the inline version? why does it fix the problem?
@jas Pattern#splitAsStream() returns a Stream<String>. If you assign that to a stream variable declared as a raw (untyped) Stream, you lose the typing. When you use the variable Stream stream, the compiler doesn't know you assigned a Stream<String> to it; the compiler only looks at the declared type, which is untyped, and compiles more or less as if it was declared as Stream<Object>.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.