mapReduce排序 筆記


在 mymapper 中加入要排序的類

	static class MyMapper extends Mapper<LongWritable, Text, NewK2, LongWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,NewK2,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
			final String[] splited = value.toString().split("\t");
			final NewK2 k2 = new NewK2(Long.parseLong(splited[0]), Long.parseLong(splited[1]));
			final LongWritable v2 = new LongWritable(Long.parseLong(splited[1]));
			context.write(k2, v2);
		};
	}

  newk2 要繼承 WritableComparable

     static class  NewK2 implements WritableComparable<NewK2>{
        Long first;
        Long second;
        
        public NewK2(){}
        
        public NewK2(long first, long second){
            this.first = first;
            this.second = second;
        }
        
        
        @Override
        public void readFields(DataInput in) throws IOException {
            this.first = in.readLong();
            this.second = in.readLong();
        }

        @Override
        public void write(DataOutput out) throws IOException {
            out.writeLong(first);
            out.writeLong(second);
        }

        /**
         * 當k2進行排序時,會調用該方法.
         * 當第一列不同時,升序;當第一列相同時,第二列升序
         */
        @Override
        public int compareTo(NewK2 o) {
            final long minus = o.first - this.first;
            if(minus !=0){
                return (int)minus;
            }
            return (int)(this.second - o.second);
        }
        
        @Override
        public int hashCode() {
            return this.first.hashCode()+this.second.hashCode();
        }
        
        @Override
        public boolean equals(Object obj) {
            if(!(obj instanceof NewK2)){
                return false;
            }
            NewK2 oK2 = (NewK2)obj;
            return (this.first==oK2.first)&&(this.second==oK2.second);
        }
    }


問:爲什麼實現該類?
答:因爲原來的v2不能參與排序,把原來的k2和v2封裝到一個類中,作爲新的k2


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章