【问题标题】:Map-reduce using java - java.lang.StringIndexOutOfBoundsException: String index out of range: 0Map-reduce 使用 java - java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0
【发布时间】:2019-09-18 01:50:39
【问题描述】:

我正在尝试编写一个 Spark 应用程序,它输出以每个字母开头的单词数。我收到一个字符串索引超出范围错误。有什么建议,还是我没有以正确的方式解决这个 map-reduce 问题?

public class Main {
    public static void main(String[] args) throws Exception{

        //Tell spark to access a cluster
        SparkConf conf = new SparkConf().setAppName("App").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        System.out.printf("%d lines\n", sc.textFile("pg100.txt").count());


        //MARK: Mapping
        //Read target file into an Resilient Distributed Dataset(RDD)
        JavaRDD<String> lines = sc.textFile("pg100.txt");

        //Split lines into individual words by converting each line into an array of words
        //Treat all words as lowercase
        //Ignore non-alphabetic characters
        JavaRDD<String> words = lines.flatMap(line -> Arrays.asList(line.split(" ")).iterator()).map(line -> line.replaceAll("[^a-zA-Z0-9_-]","").replaceAll("\\.", "").toLowerCase());

        //MARK: Sorting
        //Count the total number of words that start with each letter
        JavaPairRDD<Character, Integer> letters = words.mapToPair(w -> new Tuple2<>(w.charAt(0), 1));

        //MARK: Reducing
        //Get count of number of instances of each word
        JavaPairRDD<Character, Integer> counts = letters.reduceByKey((n1,n2) -> n1 + n2);

        counts.saveAsTextFile("result");
        sc.stop();

    }
}

【问题讨论】:

  • 您的代码 sn-p 包含 31 行,因此不清楚“第 33 行”是什么意思。您还发布了带有标签 scala 的 java 代码。请更新您的问题。

标签: java apache-spark iterator stringindexoutofbounds


【解决方案1】:

我怀疑有些词只包含被下面一行替换的字符:

JavaRDD<String> words = lines.flatMap(line -> Arrays.asList(line.split(" ")).iterator()).map(line -> line.replaceAll("[^a-zA-Z0-9_-]","").replaceAll("\\.", "").toLowerCase());

因此,一些单词变成了空字符串并且仍然保留在words RDD 中,当您尝试访问它们的 index=0 时,您自然会收到您提到的异常。

你可能认为如果 map 产生了空字符串,它就不会被包含在words 中,这不是真的。

UPD。您可以通过这种方式过滤掉空字符串:

words.filter(line -> !line.equals(""));

【讨论】:

  • 你是对的。当我输出它时,我的 RDD 中有空字符串。但是,我无法使用过滤器方法过滤掉空字符串。
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
相关资源
最近更新 更多