「Java8」ラムダ式(lambda expression)戻り値を返すサンプル

2020年11月9日

構文
インターフェース名 オブジェクト名 = () -> {
//some code
return xxx
}

使用例
(1).インターフェースの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.cft;
//インターフェース
public interface EmpInfo {
//メソッド string return value
public String func();
}
package com.arkgame.study.cft; //インターフェース public interface EmpInfo { //メソッド string return value public String func(); }
package com.arkgame.study.cft;

//インターフェース
public interface EmpInfo {
      //メソッド string return value
      public String  func();

}

(2).インターフェースの実装

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.cft;
public class InterFaceDemo {
public static void main(String[] args) {
interMethod();
}
public static void interMethod() {
EmpInfo emp = () -> {
String message = "lambda return sample";
return message;
};
System.out.println("戻り値を返す: " + emp.func());
}
}
package com.arkgame.study.cft; public class InterFaceDemo { public static void main(String[] args) { interMethod(); } public static void interMethod() { EmpInfo emp = () -> { String message = "lambda return sample"; return message; }; System.out.println("戻り値を返す: " + emp.func()); } }
package com.arkgame.study.cft;

public class InterFaceDemo {

      public static void main(String[] args) {
            interMethod();
      }

      public static void interMethod() {

            EmpInfo emp = () -> {
                  String message = "lambda return sample";
                  return message;
            };
            System.out.println("戻り値を返す: " + emp.func());
      }
}

(3).実行結果
戻り値を返す: lambda return sample

Java

Posted by arkgame