1. 2016.8.14 Hadoop Text array Sort

1.1. Problem:

  • 使用Hadoop時,我想要把傳入reduce的具有相同key的value進行排序,然後再輸出;
  • 這個問題關鍵點在於Java裡面的Text Array沒有自帶的Sort功能

1.2. Solution:

  • 先將傳入reduce的value都先add到一個新聲明的ArrayList當中

  • 然後使用ArrayList的Collection.sort方法

  • 將排序好後的ArrayList再做進一步的操作

  • 代碼如下:

      public static class StatsReducer extends Reducer<Text,Text,Text,Text>
      {
          public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException
          {
              String output_str = "X";
              ArrayList<String> myList = new ArrayList<String>();
              for (Text val : values)
              {
                  myList.add( val.toString() );
              }
              Collections.sort(myList);
              for (String str : myList)
              {
                  output_str = output_str + ";" + str;
              }
              context.write(key, new Text(output_str));
          }
      }