简体   繁体   English

如何在Spark中将ArrayList转换为Scala数组

[英]How to convert ArrayList into Scala Array in Spark

I want to create a StructType dynamically out of a json file.我想从 json 文件中动态创建一个 StructType。 I iterate my fields and I want to find out how (if it is even possible) can I create some list with my iteration, and then to create a StructType from it.我迭代我的字段,我想知道如何(如果可能的话)我可以用我的迭代创建一些列表,然后从中创建一个 StructType。

The code I've tried:我试过的代码:

List<StructField> structFieldList = new ArrayList<>();
for (String field : fields.values()) {
  StructField sf = Datatypes.createStructField(field, DataTypes.StringType, true);
  structFieldList.add(sf);
}
StructType structType = new StructType(structFieldList.toArray());

But this one is pretty impossible.但这几乎是不可能的。 Is there any way to figure this out?有什么办法可以解决这个问题吗?

Here you don't need to convert ArrayList to Scala Array , as StructType constructor takes java StructField[] array as argument.在这里您不需要将ArrayList转换为 Scala Array ,因为StructType构造函数将 java StructField[]数组作为参数。

Your code can be changed by setting type when calling .toArray() method in your last line of code snippet so it returns a StructField[] array instead of an Object[] array:在最后一行代码片段中调用.toArray()方法时,可以通过设置类型来更改代码,以便它返回StructField[]数组而不是Object[]数组:

List<StructField> structFieldList = new ArrayList<>();
for (String field : fields.values()) {
  StructField sf = DataTypes.createStructField(field, DataTypes.StringType, true);
  structFieldList.add(sf);
}
StructType structType = new StructType(structFieldList.toArray(new StructField[0]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM