2014-10-07 119 views
1

请参见“Programmatically Specifying the Schema”部分。 Java部分。Spark 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方法。

我只知道字段的数量在运行时

例如,它可能是一个:

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]); 

我该怎么做?

+0

有人提出“论点后三点”能解决我的问题。它不会。我调用的方法已经接受了一个动态数量的参数。问题在于打电话。我不知道在编译时传递给它多少个参数。我会在运行时知道它。问题不在于功能。 – Sit 2014-10-07 07:26:18

回答

0

尝试在您实施的方法中使用elipsis,如下所示。

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

Elipsis accept n参数个数。

0

您可以指定一个方法,通过论证后采用三个点取多个参数,例如:

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

更换你所需的返回类型。 请更改您的调用方法的签名,因为您尚未指定返回类型!

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); 
    } 
} 

有可能是龙。我的版本编译,看起来不错,尚未测试。

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); 
     } 
     }); 
相关问题