Spring/JAVA

[Java8 Lambda] foreach iteration

alsruds 2023. 10. 19. 01:48
🤹‍♂️Java Brains 강의🤹‍♂️

https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3

 

  • people 리스트 출력하기
    • for loop
    • for-in loop
    • for-each loop

 

External Iterator

· for & for-in loop

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Charles", "Dickens", 60),
                new Person("Lewis", "Carroll", 42),
                new Person("Thomas", "Carlyle", 51)
        );
        
        // for loop
        System.out.println("Using for Loop");
        for (int i = 0; i < people.size(); i++) {
            System.out.println(people.get(i));
        }
        
        // for-in loop
        System.out.println("Using for in loop");
        for (Person p : people) {
            System.out.println(p);
        }
    }
}

➡️ External Iterator : You are managing the interation process you are controlling

 

Internal Iterator

· for-each loop

public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Charles", "Dickens", 60),
                new Person("Lewis", "Carroll", 42),
                new Person("Thomas", "Carlyle", 51)
        );
        // for-each
        System.out.println("Using lambda for each loop");
        people.forEach(p -> System.out.println(p));
        
        // method reference : people.forEach(System.out::println);
    }
}

➡️ Internal Iterator : Giving the control to somebody else

➡️ Foreach : It is a method that takes in one argument which is a consumer

 

'Spring > JAVA' 카테고리의 다른 글

[Java8 Lambda] Streams  (0) 2023.10.20
[Java8 Lambda] Method References  (0) 2023.10.18
[Java8 Lambda] this  (0) 2023.10.17
[Java8 Lambda] Closures in Lambda Expressions  (1) 2023.10.16
[Java8 Lambda] Exception Handling in Lambdas (try - catch)  (0) 2023.10.13