複数の関数に同じ操作を実行します

lopoto:

私は複数のクラスを持つ必要がありget、このようなとしての機能をgetF1しますgetF10私は手紙を交換するために、これらのゲッターのそれぞれのために、必要"x""a"(ランダム例)。ゲッターは、NULL値を返すことができます。

これまでのところ、これは私が行っている、それがどのような作品で、これよりも良い見て何かを得るためにそこに方法は何ですか?

public void foo(final MyObject bar) {
    Optional.of(bar).map(MyObject::getF1).ifPresent(s -> bar.setF1(s.replaceAll("x", "a"));
    Optional.of(bar).map(MyObject::getF2).ifPresent(s -> bar.setF2(s.replaceAll("x", "a")));
    ...
    Optional.of(bar).map(MyObject::getF10).ifPresent(s -> bar.setF10(s.replaceAll("x", "a")));
}

私は、このような何かを考えて、リストを使用していた、明らかに、このコードは間違っているが、あなたのアイデアを得ます:

public void foo(final MyObject bar) {
    List<Function> func = new ArrayList<Function>();
    func.addAll(Arrays.asList(MyObject::getF1, MyObject::getF2, ..., MyObject::getF10));
    Optional.of(bar).map(func).ifPresent(s -> func(s.replaceAll("x", "a"));
}

たぶんストリームでの作業は、仕事を得るだろうか?

ありがとう!

ニコラス:

あなたはで使用されるマッパー保存することができますOptional::mapで使用され、消費者Optional::ifPresentにしますMap

私はまた、あなたが簡単に呼ばれなければならない文字列置換のためのコードの重複を避けるためのメソッドを作成することをお勧めします。すべての置換が同じであるので、これは便利です

private String replaced(String string) {
    return string.replaceAll("x", "a");
}

そして、単純に(順番は関係ない)のエントリを反復処理し、キーと値のペアのそれぞれに適用されます。

Map<Function<? super MyObject, ? extends String>, Consumer<? super String>> map = new HashMap<>();
map.put(MyObject::getF1, bar::setF1);
map.put(MyObject::getF2, bar::setF2);
map.put(MyObject::getF10, bar::setF10);
// ...

map.forEach((function, consumer) -> {
        Optional.of(bar).map(function).map(this::replaced).ifPresent(consumer);
});

あなたはこのメカニズムを拡張し、文字列がセッターに渡されたそれぞれに異なる機能を適用したい場合は、別の構造を使用することも必要があります。

public final class Mapping {

    private final Function<MyObject, String> getterFunction;
    private final Function<String, String> transformationFunction;
    private final Consumer<String> setterFunction;

    public Mapping(final Function<MyObject, String> getterFunction, final Function<String, String> transformationFunction,
        final Consumer<String> setterFunction) {
        this.getterFunction = getterFunction;
        this.transformationFunction = transformationFunction;
        this.setterFunction = setterFunction;
    }

    // getters
}

および使用方法は、(変換関数はサンプルであり、異なる場合があります)と同様です。

List<Mapping> list = new ArrayList<>();
list.add(new Mapping(MyObject::getF1, s -> s.replaceAll("x", "a"), bar::setF1));
list.add(new Mapping(MyObject::getF2, s -> s.replaceAll("x", "a"), bar::setF2));
list.add(new Mapping(MyObject::getF10, s -> s.replaceAll("x", "a"), bar::setF10));

list.forEach(mapping -> {
    Optional.of(bar)
            .map(mapping.getGtterFunction)
            .map(mapping.getTransformationFunction)
            .ifPresent(mapping.getSetterFunction);
});

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=200995&siteId=1