LoginSignup
1
1

More than 3 years have passed since last update.

【Java】forEachメソッド

Last updated at Posted at 2019-08-12
public class Array {

    public static void main(String[] args) {

        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee("tanaka", 25));
        list.add(new Employee("yamada", 28));
        list.add(new Employee("suzuki", 20));

        list.forEach( s -> System.out.println(s.getName() + ":" + s.getAge()));
     }
}

繰り返す実行処理が一つの場合このように一行で書けるが、複数ある場合は{}で実行処理を囲う

        list.forEach( s -> {
            System.out.println(s.getName());
            System.out.println(s.getAge());
        });

ラムダ式を使わない書き方は以下のようになる

        list.forEach(new Consumer<Employee>() {
            @Override
            public void accept(Employee e) {
                System.out.println(e.getName() + " : " + e.getAge());
            }
        });
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1