Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using forEach to iterate over varArgs [duplicate]

Tags:

java

java-8

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();
   }
like image 974
BoltClock Avatar asked Oct 13 '15 16:10

BoltClock


Video Answer


1 Answers

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 (...);
like image 166
Eran Avatar answered Oct 19 '22 12:10

Eran