| 20行目: | 20行目: | ||
public class FuncList { | public class FuncList { | ||
public static boolean isOdd(int x) { return (x % 2 == 1); } | public static boolean isOdd(int x) { return (x % 2 == 1); } | ||
public static String | public static String addMr(boolean male, String name) { | ||
if (male == true) { return "Mr." + name; } | if (male == true) { return "Mr." + name; } | ||
else { return "Ms." + name; } | else { return "Ms." + name; } | ||
| 37行目: | 37行目: | ||
public static void main(String[] args) { | public static void main(String[] args) { | ||
Func1 f1 = FuncList::isOdd; | Func1 f1 = FuncList::isOdd; | ||
Func2 f2 = FuncList:: | Func2 f2 = FuncList::addMr; | ||
System.out.println(f1.call(15)); | System.out.println(f1.call(15)); | ||
System.out.println(f2.call(true, "Smith")); | System.out.println(f2.call(true, "Smith")); | ||
} | } | ||
2019年7月2日 (火) 18:10時点における版
< Java基本文法
- 機能オブジェクトとは、クラス内のメソッドを再利用するための仕組み
- メソッドを定義することなくロジックを利用したい場合はラムダ式が利用できる
- 機能オブジェクトを格納するには同じ戻り値と引数を定義したSAMインターフェースを使う
import java.util.function.*;
public class Main {
public static int sub(int a, int b) {
return a - b;
}
public static void main(String[] args) {
IntBinaryOperator func = Main::sub;
int ans = func.applyAsInt(5, 3);
System.out.println("5 - 3" + ans);
}
}
例
# FuncList.java
public class FuncList {
public static boolean isOdd(int x) { return (x % 2 == 1); }
public static String addMr(boolean male, String name) {
if (male == true) { return "Mr." + name; }
else { return "Ms." + name; }
}
}
# Main.java
interface Func1 {
boolean call(int x);
}
interface Func2 {
String call(boolean male, String name);
}
public class Main {
public static void main(String[] args) {
Func1 f1 = FuncList::isOdd;
Func2 f2 = FuncList::addMr;
System.out.println(f1.call(15));
System.out.println(f2.call(true, "Smith"));
}