Spark Java:将可变数量的参数传递给函数

时间:2014-10-07 05:58:06

标签: java apache-spark

请参阅“Programmatically Specifying the Schema”部分。 Java部分。

该示例有效。但是我对这个特定的代码片段有疑问。

JavaRDD<Row> rowRDD = people.map(
new Function<String, Row>() {
public Row call(String record) throws Exception {
String[] fields = record.split(",");
  return Row.create(fields[0], fields[1].trim());
}

使用在编译时确定的静态对象数来调用Row create方法。

但是,在我的代码中,我需要为动态数量的参数调用Row.create方法。

我只会知道运行时的字段数

例如,它可能是以下之一:

return Row.create(fields[0], fields[1].trim(), fields[2]);

return Row.create(fields[0]);

return Row.create(fields[0],fields[1].trim(), fields[2], fields[3],fields[4]);

我该怎么办?

4 个答案:

答案 0 :(得分:1)

以下是如何做到这一点。为我工作。

JavaRDD<Row> rowRDD = people.map(
  new Function<String, Row>() {
   public Row call(String record) throws Exception {
     String[] fields = record.split(",");         
    //return Row.create(fields[0], fields[1].trim());
      Object[] fields_converted = fields;
      return Row.create(fields_converted);
      }
      });

答案 1 :(得分:0)

尝试在实现的方法中使用省略号,如下所示。

public static void create(String ...arg) { ... }

除了n个参数之外的省略号。

答案 2 :(得分:0)

您可以通过在参数后面使用三个点指定一个方法来获取多个参数,例如:

public static <return_type> create(String...args){
    // Yoo can now use the String[] args
}

替换为您想要的返回类型。 请更改调用方法的签名,因为您没有为其指定退货类型!

答案 3 :(得分:0)

以下是我在同样情况下所做的事情

new Function<String, Row>(String s) {
    public Row call(String s){
        int n = /* width of actual schema */
        Object rec[] = new Object[n];
        for( int i = 0; i < n; ++i )
            rec[i] = /* Something that aligns with the type of #i field */
        return Row.create( rec );
    }
}

这里可能有龙。我的版本编译,看起来很好,尚未测试。

相关问题