2016-10-10 60 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

謝謝!它真的有效。我完全不知道這個問題。 –