LoginSignup
0
1

More than 3 years have passed since last update.

【Java】関数型インターフェース

Last updated at Posted at 2019-08-13

関数型インターフェースとは

抽象メソッドを一つだけ持つインターフェース(staticメソッドやdefaultメソッドは無視される)

◆Functio<T,R>

・受け取った引数の値を変換する
・T=メソッドの引数の型、R=メソッドの戻り値の型
・抽象メソッドは R apply(T t)

Function<Integer,String> func = f -> f + "になる";
String s =  func.apply(1);
System.out.println(s); //1になる

◆Consumer<T>

・受け取った引数を使って処理を行う(戻り値なし)
・T=メソッドの引数の型
・抽象メソッドは accept(T t)

Consumer<String> dog = e -> System.out.println("hello," + e);
dog.accept("柴犬");//hello,柴犬

ラムダ式を使わず書くと下記のようになる

Consumer<String> dog = new Consumer<String>() {
    @Override
    public void accept(String name) {
                System.out.println("hello," + name);//hello,柴犬
    }

◆Predicate<T>

・受け取った引数で判定を行いBooleanを返す
・T=メソッドの引数の型
・抽象メソッドは test(T)

Predicate<String> result = c -> {return c.equals("dog");}; 
boolean animal = result.test("cat");
System.out.println(animal);//false
0
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
0
1