2016-10-10 65 views
2

下面是Hadoop Reducer的代码,我无法理解为什么比较(放在斜线之间)总是失败,我们在这里比较两个文本类型值。此代码适用于Reducer进行反向索引。Hadoop文本比较不起作用

public static class IntSumReducer 
     extends Reducer<TextPair, Text, Text, Text>{ 

    private Text indexedData = new Text(); 

    public void reduce(TextPair key, Iterable<Text> values, Context context) 
      throws IOException, InterruptedException { 

     Iterator<Text> itr = values.iterator(); 
     Text oldValue = itr.next() ; 
     String old = oldValue.toString(); 

     //String next; 
     int freq = 1; 
     Text nextValue = null; 
     StringBuilder stringBuilder = new StringBuilder(); 

     if(itr.hasNext()==false) { 
      stringBuilder.append(old + 1); 
     } 

     while(itr.hasNext()) { 
      nextValue = itr.next();   
      int compareValue = oldValue.compareTo(nextValue); 

      while(compareValue == 0) { 
       freq++; 

       if(itr.hasNext()) { 
        nextValue = itr.next(); 

        //////////////////////////// 
        // following comparison always returning zero 
        // Although values are changing 
        compareValue = oldValue.compareTo(nextValue); 
        /////////////////////////// 

        System.out.println(compareValue); 

       } else { 
        freq++; 
        System.out.println("Break due to data loss.."); 
        break; 
       }    
      }//end while 
      System.out.println("Value Changed.."); 
      old = old + freq; 
      stringBuilder.append(old); 
      stringBuilder.append(" | "); 
      oldValue = nextValue; 
      old = nextValue.toString(); 
      freq = 1; 

     }//endwhile 

     //System.out.println("KEY :: " + key.toString()); 
     context.write(key.getFirst(),new Text(stringBuilder.toString())); 
    } 
} 

任何帮助表示赞赏,因为我完全是这方面的新手。

回答

2

您的问题最有可能与Iterable<Text>重新使用Text对象这一事实有关,因此它每次都不会为您提供新对象,而只是重用相同的对象。

在您需要更改这两行最低:

Text oldValue = itr.next(); 
oldValue = nextValue; 

要:

Text oldValue = new Text(itr.next()); 
oldValue.set(nextValue); 

否则你只是比较同一对象,因为oldValue将被物体你”总是指向再比较一下。

+0

谢谢!它真的有效。我完全不知道这个问题。 –