using forEach to iterate over varArgs [duplicate]

ぃ、小莉子 提交于 2019-12-30 08:13:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!