簡體   English   中英

BiFunction <>與枚舉

[英]BiFunction<> with Enum

我正在使用BiFunction來發送函數。

我現在所擁有的是:

public class Animal {
    public static String cat(
        final String field,
        final Object value
    ) {
        return "(CAT:" + field + toString(value) + ")";
    }

    public static String dog(
        final String field,
        final Object value
    ) {
        return "(DOG:" + field + toString(value) + ")";
    }
}

public String getAnimal(
    final String animalFieldName,
    final BiFunction<String, Object, String> function,
    final Object animelieldValue
) {
    return function.apply(animalFieldName, animalFieldValue);
}

我這樣使用它:

new Animal("catName", Animal::cat, "catti")

我想要的是BiFunction <>將是一個枚舉,因此getAnimal()的簽名將是:

String getAnimal(
    final String animalFieldName,
    /* Enum that has values that are BiFunctions, */
    final Object animalFieldValue
)

有什么建議么? 我希望代碼示例。

不太確定您想要什么,但這似乎符合要求嗎?

enum Animal implements BiFunction<String, Object, String> {
    CAT,
    DOG,
    BEAR {
        @Override
        public String apply(String s, Object o) {
            return "This is a Bear!!!";
        }
    };

    @Override
    public String apply(String s, Object o) {
        return "(" + name() + ":" + s + o.toString() + ")";
    }
}

public void test() {
    for (Animal animal : Animal.values()) {
        System.out.println(animal.apply("hello", "Hello"));
    }
}

@OldCurmudgeon答案的變體,其中包含更多的lambda:

enum Animal implements BiFunction<String, Object, String> {
    CAT,
    DOG,
    BEAR((s, o) -> "This is a Bear!!!");

    private final BiFunction<String, Object, String> function;

    private Animal(final BiFunction<String, Object, String> function) {
        this.function = function;
    }

    private Animal() {
        super((s, o) -> "(" + name() + ":" + s + o.toString() + ")");
    }
}

public void test() {
    Animal
        .values()
        .stream(animal -> animal.apply("hello", "Hello"))
        .forEach(System.out::println)
    ;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM