Domanda

I'm coming at some functional java from a ruby point of view

in ruby you can do something like this

mapped_array = [1,2,3].map(&:to_s)

which evaluates out to transforming (map) the array by calling the to_s member function on each object

mapped_array = []
[1,2,3].each { |e| mapped_array << e.to_s }

I'd like to do something similar in Java, namely transform a list of Product-3 (fj.P3) by calling the _2() method on each object

List<P2<Integer, Double>> aListOfP2;
final List<Double> costs = transform(aListOfP2, Converters.<Integer, Double>second());

so I have had to define somewhere a method

public static final <A,B> Function<P2<A,B>,B> second() {
    return new Function<P2<A, B>, B>() {
        public B apply(final P2<A, B> from) {
            return from._2();
        }
    };
};

but then if I want to get the first element, that is another method... if I want to get the second element from a P3, that is another method.

Question is... If there is no mechanism like available in ruby, what is the most generic way to accomplish this?

È stato utile?

Soluzione

you should check out __2(), as in, two underscores.

so your line would become:

List<P2<Integer, Double>> aListOfP2;
final List<Double> costs = transform(aListOfP2, P2.<Integer, Double>__2());

or you could use something like

final List<Double> costs = aListOfP2.map(P2.__2()).map(transform);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top