Edu
Edu

Reputation: 73

How can I convert a custom Java class to a Spark Dataset

I can't figure out a way to convert a List of Test objects to a Dataset in Spark This is my class:

public class Test {
    public String a;
    public String b;
    public Test(String a, String b){
        this.a = a;
        this.b = b;
    }

    public List getList(){
        List l = new ArrayList();
        l.add(this.a);
        l.add(this.b);

        return l;
    }
}

Upvotes: 7

Views: 8975

Answers (1)

Anton Okolnychyi
Anton Okolnychyi

Reputation: 966

Your code in the comments to create a DataFrame is correct. However, there is a problem with the way you define Test. You can create DataFrames using your code only from Java Beans. Your Test class is not a Java Bean. Once you fix that, you can use the following code to create a DataFrame:

Dataset<Row> dataFrame = spark.createDataFrame(listOfTestClasses, Test.class);

and these lines to create a typed Dataset:

Encoder<Test> encoder = Encoders.bean(Test.class);
Dataset<Test> dataset = spark.createDataset(listOfTestClasses, encoder);

Upvotes: 4

Related Questions