11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

java8 メソッド参照

Last updated at Posted at 2017-05-16

前書き

forEachの使用方法でラムダ式を用いた方法しか知らなかったのですが、メソッド参照「::」を用いた方法もあったのでメモ。

メソッド参照

クラス名(インスタンス)::メソッド名

のように記述することで、メソッドの参照が可能

forEach例

メソッド参照

list.forEach(System.out :: println);

ラムダ式

list.forEach(x -> System.out.println(x));

使用例

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        Main main = new Main();
        System.out.println("----No1----");
        main.test().forEach(main :: myPrint);
        System.out.println("----No2----");
        main.test().forEach(x -> main.myPrint(x));
        
    }
    
    public List<String> test(){
        List<String> list = new ArrayList<>();
        list.add("AA");
        list.add("BB");
        list.add("CC");
        list.add("DD");
        return list;
    }
    
    public void myPrint(String str){
        System.out.println(str);
    }
}


インスタンスの持つメソッドを呼び出す例ですが、実行結果はどちらも同じです。

実行結果

----No1----
AA
BB
CC
DD
----No2----
AA
BB
CC
DD
11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?