Class

Function Type

Function<T, R>

T => R

DoubleFunction<T>

T => Double

PairFunction<T, K, V>

T => Tuple2<K, V>

FlatMapFunction<T, R>

T => Iterable<R>

DoubleFlatMapFunction<T>

T => Iterable<Double>

PairFlatMapFunction<T, K, V>

T => Iterable<Tuple2<K, V>>

Function2<T1, T2, R>

T1, T2 => R (function of two arguments)

 每个类都有一个抽象的类方法call(),实现类必须实现该方法。

1. Function<T, R>

该类表示将T转换为R。

JavaRDD<String> map = logData.map(new Function<String, String>() {
            @Override
            public String call(String s) throws Exception {
                return s + " add";
            }
        });

上述代码的将logData中的每个字符串转换为一个新的字符串,方法是在原来的字符串上,增加一个固定字符串" add"。

2. DoubleFunction<T>

将T转换为Double。也可以用Function<T, Double>代替。

DoubleFunction<String> doubleFunction = new DoubleFunction<String>() {
            @Override
            public double call(String s) throws Exception {
                return Double.valueOf(s).doubleValue();
            }
        };

3. PairFunction<T, K, V>

将T转换为Tuple2<K, V>,将一个元素转换为一个元组。

JavaPairRDD<String, Integer> javaPairRDD = logData.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }
        });

以上代码将一个字符串RDD转换一个元组RDD。

4. Function2<T1, T2, R>

T1, T2 => R,方法包含两个参数,T1,T2为输入参数,R为返回值

Function2<Long, Long, Long> function2 = new Function2<Long, Long, Long>() {
            @Override
            public Long call(Long t1, Long t2) throws Exception {
                return t1 + t2;
            }
        };

以上为将两个参数求和返回的实现。