LoginSignup
1
0

More than 1 year has passed since last update.

【Java】関数型インターフェース(Function)の使い方

Posted at

Functionインターフェースとは?

Functionは1つの引数(Type T)を受けて、1つのオブジェクト(Type R)を返す関数型インターフェースです。

public interface Function<T, R> {

    R apply(T t);
}

使い方

以下の例では、func1apply()メソッドにHelloを引数として渡すことで、Hello World!が返されます。

import java.util.function.Function;

public class FunctionExample1 {

    public static void main(String[] args) {

        Function<String, String> func1 = x -> x + " World!";

        String result = func1.apply("Hello");

        System.out.println(result); // Hello World!
    }
}

以下は、匿名クラスでFunctionインターフェースを使用する例です。

import java.util.function.Function;

public class FunctionExample2 {

//不規則なリストを作成
List<Integer> randomNumbers = new ArrayList<>(Arrays.asList(378,121,190));

//リストをソートするメソッドを定義
List<Integer> sortedList = new Function<List<Integer>,List<Integer>>() {
    @Override
    public  List<Integer> apply(List<Integer> randomNumbers ) {
        Collections.sort(randomNumbers);
        return randomNumbers;
    }
//不規則なリストを引数として渡す
}.apply(randomNumbers);

//ソート済のリストを出力
for (Integer sortedNum:sortedList) {
    System.out.println(sortedNum); //121 190 378
    }
}

参照

Java Platform SE8 #Function

1
0
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
0