0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【 Java 】スッキリわかるJava 実践編 ラムダ練習問題

Last updated at Posted at 2023-08-11

#スッキリわかるJava 実践編 ラムダ練習問題

◾️ 練習問題3_1

FuncListクラス
public class FuncList {
    
    public static boolean isOdd(int x) {
        return (x % 2 == 1);
    }
    
    public String passCheck(int point, String name) {
        return name + "さんは" + (point > 65 ? "合格" : "不合格");
    }
}
Func1 / Func2 インタフェース
public interface Func1 { boolean call(int x); }

public interface Func2 { String call(int point, String name); }
Mainクラス 問題 3_1
public static void main(String[] args) {

    FuncList func = new FuncList();
    // FuncListクラスに定義した静的メソッドの参照を変数に代入
    Func1 f1 = FuncList::isOdd;
    // FuncListクラスに定義したメソッドの参照をインスタンス変数を通して代入
    Func2 f2 = func::passCheck;
    
    System.out.println(f1.call(15));
    System.out.println(f2.call(65, "Test"));
}

◾️ 練習問題3_2

Mainクラス 問題 3_2
public static void main(String[] args) {
    // FuncListの各メソッドをラムダ式で表現
    Func1 f1 = x -> x % 2 == 1;
    Func2 f2 = (point, name) -> {
        return name + "さんは" + (point > 65 ? "合格" : "不合格");
    };
    System.out.println(f1.call(15));
    System.out.println(f2.call(65, "Test"));
}

◾️ 練習問題3_3

Mainクラス 問題 3_3
public static void main(String[] args) {
    // Func1,2を標準関数インタフェースに変更
    // IntPredicate = Int値の引数を評価
    IntPredicate isOdd = x -> x % 2 == 1;
    // Predicate<xxx> = xxx値の引数を評価
    Predicate<Integer> f1 =  x -> x % 2 == 1;
    
    // <Integer = 引数1(point), String = 引数2(name) , String = 戻り値>
    BiFunction<Integer,String, String> passCheck = (point, name) -> {
        return name + "さんは" + (point > 65 ? "合格" : "不合格");
    };
    
    // f1とisOddの結果は同じ
    System.out.println(f1.test(15));
    System.out.println(isOdd.test(15));
    System.out.println(passCheck.apply(65, "Test"));
}

◾️ 練習問題3_4

Mainクラス 問題3_4
public static void main(String[] args) {
    // 登場人物を格納
    List<String> names = List.of("菅原拓真", "大江岳斗", "朝香あゆみ", "湊雄介");
    
    // フルネームが4文字以下の人にの末尾に「さん」をつける StreamAPIを使う
    names.stream()
        .filter(name -> name.length() <= 4)
        .map(name -> name + "さん")
        .forEach(System.out::println);
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?