java - mapreduce错误:java.lang.indexoutofboundsexception:index:2,size:2

标签 java eclipse hadoop

我将hadoop与eclipse连接,通过eclipse插件启动该作业,mapreduce作业可以成功完成,但是当我将代码编译到jar文件中,然后通过hadoop命令执行此作业时,它将引发以下错误。

Error:java.lang.IndexOutOfBoundsException:Index:1,Size:1
      at java.util.ArrayList.rangecheck(Arraylist.java:635)
      at java.util.ArrayList.get(ArrayList.java:411)
      at Combiner.reduce(Combiner.java:32)
      at Combiner.reduce(Combiner.java:1)

和我的代码如下:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;


public class Combiner extends MapReduceBase implements Reducer<Text,Text,Text,Text>{
    public void reduce(Text       key,Iterator<Text>values,OutputCollector<Text,Text>output,Reporter reporter)
            throws IOException{
        int num=3;
        Comparator<String> comparator=new MyComparator();
        PriorityQueue<String> queue=new PriorityQueue<String>(100,comparator);
        ArrayList<String> list=new ArrayList<String>();
        while(values.hasNext()){
            String str=values.next().toString();
            queue.add(str);
        }
        while(!queue.isEmpty()){

            list.add(queue.poll());

        }
        String getCar="";
        for(int i=0;i<num;i++){
            getCar=getCar+list.get(i)+"\n";

        }
        output.collect(new Text(""), new Text(getCar));
    }

    public class MyComparator implements Comparator<String>{
        public int compare(String s1,String s2){
            if(Long.parseLong(s1.split(",")[4])>Long.parseLong(s2.split(",")[4])){
                return 1;
            }else if(Long.parseLong(s1.split(",")[4])<Long.parseLong(s2.split(",")[4])){
                return -1;
            }else{
                return 0;
            }
        }
    }
}

最佳答案

发生这种情况是因为列表中有一个元素(Size:1),而您要求第二个元素(Index:1-索引从零开始)!每个列表元素的简单System.out.println将帮助您完成...

为什么将元素数设置为3?如果您知道它将为3(不太可能),则将列表更改为大小为3的数组。如果不知道,则将num更改为list.size(),例如:

for(int i=0;i<list.size();i++)

但是在进行其他操作之前,您应该了解为什么要为此键获得这些值。

关于java - mapreduce错误:java.lang.indexoutofboundsexception:index:2,size:2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23602001/

相关文章:

c++ - 使用 Eclipse CDT 进行 Pintool 开发

android - 模拟器控制android被禁用

java - TextureAtlas 区域到 Texture

java - 对对象数组进行排序时使用 2 个排序标准的 Comparable

c - eclipse 编辑器无法识别 C#define 指令

hadoop - 没有Reducer的情况下Map任务结果

hadoop - Hadoop: yarn 和本地内存的使用

hadoop - Kafka 主题与 Kafka Connect to HDFS 合并

java - 如何加密管理员密码?

java - "Invalid column index"尝试插入行时出现 SqlException 错误