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?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments