「Java8」関数型(Function)インタフェースを使うサンプル

2020年11月9日

構文
(1).java.util.function.Function<String, Integer>
1つの引数を受け取って結果を生成する関数を表します。
これは、apply(Object)を関数メソッドに持つ関数型インタフェースです。
(2).Integer java.util.function.Function.apply(String t)
指定された引数にこの関数を適用します。
パラメータ:t – 関数の引数戻り値:関数の結果
Functionインタフェースが基本になる関数型インタフェースで、引数ひとつで戻り値をもつ関数をあらわします。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.cft;
import java.util.function.Function;
public class ListDemo {
public static void main(String[] args) {
String tarA = "testdemo";
System.out.println("文字列Aの文字数:" + interMethod(tarA));
// methodを呼び出す
String tarB = "testdemo_12#!";
System.out.println("文字列Bの文字数:" + interMethod(tarB));
}
//method definition
public static int interMethod(String target) {
// Functionインタフェース
Function<String, Integer> cft = str -> str.length();
// applyメソットを呼び出す
int length = cft.apply(target);
return length;
}
}
package com.arkgame.study.cft; import java.util.function.Function; public class ListDemo { public static void main(String[] args) { String tarA = "testdemo"; System.out.println("文字列Aの文字数:" + interMethod(tarA)); // methodを呼び出す String tarB = "testdemo_12#!"; System.out.println("文字列Bの文字数:" + interMethod(tarB)); } //method definition public static int interMethod(String target) { // Functionインタフェース Function<String, Integer> cft = str -> str.length(); // applyメソットを呼び出す int length = cft.apply(target); return length; } }
package com.arkgame.study.cft;

import java.util.function.Function;

public class ListDemo {

      public static void main(String[] args) {

            String tarA = "testdemo";
            System.out.println("文字列Aの文字数:" + interMethod(tarA));
            // methodを呼び出す
            String tarB = "testdemo_12#!";
            System.out.println("文字列Bの文字数:" + interMethod(tarB));
      }
      //method definition
      public static int interMethod(String target) {
            // Functionインタフェース
            Function<String, Integer> cft = str -> str.length();
            // applyメソットを呼び出す
            int length = cft.apply(target);
            return length;

      }
}

実行結果
文字列Aの文字数:8
文字列Bの文字数:13

Java

Posted by arkgame