问题
Can I use forEach() or stream() on varArgs ?
protected void getSomeIds (List<String>... varArgs) {
for(List lst:varArgs) {
System.out.println("This works");
}
//Following does not compile
varArgs.forEach();
// nor
varArgs.stream();
}
回答1:
Varargs behave similarly to arrays, so you can get a Stream of the varargs using Stream.of :
Stream<List<String>> stream = Stream.of (varArgs);
And you can iterate over them with :
Stream.of(varArgs).forEach (...);
回答2:
You are confusing syntax. Try this:
for(List lst:varArgs) {
lst.forEach(str -> System.out.println(str));
}
来源:https://stackoverflow.com/questions/33107636/using-foreach-to-iterate-over-varargs