简体   繁体   中英

How to use flatmap in Java with personalized objects

I'm trying to flattened an RDD that contains multiple lists of PageLinks (personalized object).

This is what i want to do :

JavaRDD<List<PageLink>> lines = sc.textFile(args[0])
                .filter(s -> s.startsWith("INSERT INTO")) // Only INSERT INTO lines
                .map(s -> s.substring(31)) // Substract 'INSERT INTO `pagelinks` VALUES ' from the line
                .map(s -> getValues(s));

        JavaRDD<PageLink> pageLinks = lines.flatMap();

This is my PageLink class:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.dekimpe.types;
import java.io.Serializable;

/**
 *
 * @author Coreuh
 */
public class PageLink implements Serializable {

    private int pl_id;
    private String pl_title;

    public int getId() {
        return pl_id;
    }

    public String getTitle() {
        return pl_title;
    }

    public void setId(int pl_id) {
        this.pl_id = pl_id;
    }

    public void setTitle(String pl_title) {
        this.pl_title = pl_title;
    }

    public String toString() {
        return "Pagelink : {'pl_id': " + this.pl_id + ", 'pl_title': '" + this.pl_title + "'}";
    }

}

I want to do this because I want to create a DataFrame with the PageLinks I get :

Dataset<Row> df = spark.createDataFrame(pageLinks, PageLink.class);
        df.limit(100).show();

You need to return iterator inside the .flatMap()

JavaRDD<PageLink> pageLinks = lines.flatMap(list -> list.iterator());

the last function while computing lines can be a flatMap() instead of map() if you need to do in a single statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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