8章7

このJavaコードは、ラムダ式を使用しています。ラムダ式は、関数的インターフェイスを簡潔に記述するための構文です。関数的インターフェイスとは、抽象メソッドを1つだけ持つインターフェイスのことを指します。

このコードにおけるラムダ式 (str) -> { return Integer.parseInt(str); } は、String を引数にとり、それを Integer に変換する処理を定義しています。このようなインターフェイスは java.util.function パッケージにある Function<T,R> に該当します。ここで、T は入力の型(この場合は String)、R は結果の型(この場合は Integer)です。

選択肢を見ると、以下の関数的インターフェイスが考えられます:

  • Consumer<T>: 引数を1つ受け取り、値を返さない(消費するだけ)。
  • Function<T,R>: 引数を1つ受け取り、何らかの値を返す。
  • Supplier<T>: 引数を受け取らず、値を供給する。
  • Predicate<T>: 引数を1つ受け取り、booleanを返す。

ラムダ式が String を受け取り、Integer を返しているので、これは Function<T,R> インターフェイスの定義に一致します。したがって、空欄には Function が正しい答えとなります。

それでは、コードにコメントを加えて説明します。

import java.util.function.*; // java.util.functionパッケージをインポート public class Main { public static void main(String[] args) { // Functionインターフェースの宣言。Stringを受け取り、Integerに変換する。 Function<String, Integer> func = (str) -> { return Integer.parseInt(str); // StringをIntegerに変換する }; // Functionインターフェースのapplyメソッドを呼び出し、"100"をIntegerに変換してから2倍する System.out.println(func.apply("100") * 2); }
}
Enter fullscreen mode
Exit fullscreen mode

上記のコメントアウトは、コードの各部分が何をしているのかを説明するために加えました。Function インターフェースは apply メソッドを持っており、これは一つの引数を受け取って処理を行い、結果を返します。この例では、apply メソッドが "100" という String を受け取り、Integer.parseInt メソッドを使って Integer に変換し、それを2倍にしています。この処理は関数的インターフェイス Function の特性に完全に一致するため、答えはB(Function)です。


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
India's largest digital store. Unlock your tech potential : download the best free software for your needs best free software download. Free 2025 jamb questions and answer /2025 jamb cbt questions & answers |free jamb 2025 answers.