3

I've been learning how to use streams and lambda expressions, and came across this question.

What is the difference between:

Arrays.asList(myDogs).forEach((d) -> {System.out.println(d.toString());
                                            actAsDog(d);});

and this:

Arrays.asList(myDogs).stream().forEach((d) -> {System.out.println(d.toString());
                                                    actAsDog(d);});

They both produce the exact same result, one by making a stream of the list and the other by using an iterator. Is there any other differences that I don't know about, and is one better than the other?

zephos2014
  • 331
  • 1
  • 2
  • 13
  • Don't forget `Stream.of(myDogs).forEach`! – yshavit Sep 15 '14 at 18:36
  • 1
    Well, if `asList().forEach()` makes an iterator instead of a stream then that would be the difference, right? However streams and iterators are different (and there should be some large differences, if you look) then that's the answer. – markspace Sep 15 '14 at 18:36
  • 1
    Why use `Arrays.asList(myDogs).stream()` instead of `Arrays.stream(myDogs)`? – bcsb1001 Sep 15 '14 at 18:36
  • Because you can't use .stream() on arrays. – zephos2014 Sep 15 '14 at 18:38
  • 1
    Take a look at this article (especially page 2). You will find the differences between your methods and benchmarks as well. http://www.javaworld.com/article/2461744/java-language/iterating-over-collections-in-java-8.html – eickeee Sep 15 '14 at 18:39
  • 1
    @zephos2014 I know, but I proposed `Arrays.stream(myDogs)`, **not** `myDogs.stream()`. – bcsb1001 Sep 15 '14 at 18:40
  • Oh yeah. I see that now. Thank you. Didn't know about that method. – zephos2014 Sep 15 '14 at 18:42

0 Answers0