Java Gold合格への道 ~関数型インタフェース・特殊化型~
スポンサーリンク
こんにちは。たろすです。
今回はjava.util.functionパッケージにあらかじめ用意されている関数型インタフェースの特殊化型について説明します。
基本の型がわからない方はこちらからご覧ください。
https://talosta.hatenablog.com/entry/java-util-functiontalosta.hatenablog.com
プリミティブ特殊化型
基本となるインタフェース(Supplier、Predicate、Consumer、Function)においてジェネリクスだった部分がプリミティブ型になっているインタフェースです。
以下のようなものがあります。
Supplier | Predicate | Consumer | Function |
---|---|---|---|
IntSupplier LongSpplier DoubleSupplier BooleanSupplier |
IntPredicate LongPredicate DoublePredicate |
IntConsumer LongConsumer DoubleConsumer |
IntFunction LongFunction DoubleFunction |
使い方の例は以下のようになります。
IntSupplier intSupplier = () ->3;
System.out.println(intSupplier.getAsInt());
型変換プリミティブ特殊化型
ConsumerとFunctionには型変換プリミティブ特殊化型と呼ばれるインタフェースがあります。
(黒本では型変換プリミティブ特殊化型と書かれていますが、調べても出てこないので一般的な呼称ではないようです)
以下のようなものがあります。
Consumer | Function |
---|---|
ObjIntConsumer ObjLongConsumer ObjDoubleConsumer |
ToIntFunction ToDoubleFunction ToLongFunction IntToDoubleFunction IntToLongFunction LongToIntFunction LongToDoubleFunction DoubleToIntFunction DoubleToLongFunction |
使い方の例は以下のようになります。
Obj*Consumer
任意の型の引数一つとプリミティブ型の引数一つを受け取り、消費します。
ObjIntConsumer<String> objIntConsumer = (str, num) -> System.out.println(str + num); objIntConsumer.accept("num:", 7);
*To*Function
引数一つを受け取り、プリミティブ型の戻り値を返します。
ToIntFunction<String> toIntFunction = str -> Integer.parseInt(str);
System.out.println(toIntFunction.applyAsInt("5"));
その他の特殊化型
Predicate、Consumer、Functionにはほかにも特殊化型のインタフェースがあります。
Predicate | Consumer | Function |
---|---|---|
BiPredicate | BiConsumer | UnaryOperetor IntUnaryOperator LongUnaryOperator DoubleUnaryOperator BiFunction ToIntBiFunction ToLongBiFunction ToDoubleBiFunction BinaryOperator IntBinaryOperator LongBinaryOperator DoubleBinaryOperator |
使い方の例は以下のようになります。
BiPredicate
任意の型の引数二つを受け取り、boolean型の戻り値を返します。
BiPredicate<String, String> biPredicate = (str1, str2) -> str1.equals(str2); System.out.println(biPredicate.test("abc", "def"));
BiConsumer
任意の型の引数二つを受け取り、消費します。
BiConsumer<String, String> biConsumer = (str1, str2) -> System.out.println(str1 + str2); biConsumer.accept("abc", "def");
*UnaryOperator
単項演算子を意味しています。
引数一つを受け取り、引数と同じ型の戻り値を返します。
UnaryOperator<Integer> unaryOperator = num -> num + 1; System.out.println(unaryOperator.apply(1));
*BiFunction
引数二つを受け取り、戻り値を返します。
BiFunction<String, String, String> biFunction = (str1, str2) -> str1 + str2; System.out.println(biFunction.apply("aaa", "bbb"));
*BinaryOperator
二項演算子を意味しています。
引数二つを受け取り、引数と同じ型の戻り値を返します。
BinaryOperator<Integer> binaryOperator = (num1, num2) -> num1 + num2; System.out.println(binaryOperator.apply(3, 5));
おわりに
今回はjava.util.functionパッケージにあらかじめ用意されている関数型インタフェースの特殊化型について説明しました。