0

Where does this forEach method come from in the following code? It was a suggested fix, and I have not written a forEach method and as far as I can find, List does not implement one either.

List<String> players = Arrays.asList(temp);
//using lambda expression and functional operations
players.forEach(person) -> System.out.print(person + "; "));

How does it know to iterate over the entire list and perform the given lambda expression?

bmcentee148
  • 594
  • 1
  • 7
  • 18
  • 4
    it was a method from [`Iterable`](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html) interface – DnR Nov 07 '14 at 05:55
  • possible duplicate of [How to break or return from Java8 Lambda forEach?](http://stackoverflow.com/questions/23308193/how-to-break-or-return-from-java8-lambda-foreach) – Kick Buttowski Nov 07 '14 at 05:58
  • 2
    I disagree on the duplicate. That thread vaguely discusses when or not to use the `forEach` method, they do not discuss where it comes or what it has to do with lambdas. – bmcentee148 Nov 07 '14 at 06:04
  • FYI, there should not be a right parenthesis after the first `person`. I.e. `players.forEach(person -> System.out.print(person + "; "));` – ajb Nov 07 '14 at 06:19

1 Answers1

3

List implements Iterable which contains forEach.

When in doubt, check the documentation (see "Methods inherited from interface java.lang.Iterable" section).

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • Thanks a bunch, I thought I thoroughly checked through to see if the method was defined but I missed it. – bmcentee148 Nov 07 '14 at 06:11
  • 1
    @bmcentee148 Inherited members aren't always obvious in javadocs since they aren't in the main list. It often also helps to do a text search on the page in case it is buried somewhere. – Jason C Nov 07 '14 at 06:11