如何在map中按降序对数据进行排序?

时间:2017-03-19 12:57:55

标签: hadoop mapreduce hadoop2

我的减速器给出了这个o / p

Country-Year,Medals
India-2008,60
United States-2008,1237
Zimbabwe-2008, 2
Namibia-2009,22
China-2009,43
United States-2009,54

我想要这个,排序应该根据奖牌进行,并且应该显示前三名。

Country-Year,Medals
United States-2008,1237
India-2008,60
United States-2009,54

有人建议我在自定义记录阅读器中进行这种排序(理解它在mapper部分中使用),我浏览了一些资源,但在排序方面找不到多少。请分享任何想法或链接到资源。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以实施Map Reduce Top K设计模式以实现您的目标。

Top K设计模式将对值记录进行排序,并选择前k个记录。

您可以通过this link在数据上实施Top K Design模式。

答案 1 :(得分:-1)

当您在Reducer类中聚合mapper的结果而不是将其写入输出时,将其带入地图,然后对地图进行排序并相应地显示结果。

Key = Country-Year,Value =奖牌 虚拟代码,展示如何实现

public class Medal_reducer extends Reducer<Text,IntWritable, Text , IntWritable> {
 // Change access modifier as per your need 
 public Map<String , Integer > map = new HashMap<String , Integer>();
 public void reduce(Text key , Iterable<IntWritable> values ,Context context )
   {
    // write logic for your reducer 
    // Enter reduced values in map for each key
    for (IntWritable value : values ){

        // calculate count
    }
     map.put(key.toString() , count); 



     }

   public void cleanup(Context context){ 
    //Cleanup is called once at the end to finish off anything for reducer
    //Here we will write our final output
     Map<String , Integer>  sortedMap = new HashMap<String , Integer>();
    sortedMap = sortMap(map);

    for (Map.Entry<String,Integer> entry = sortedMap.entrySet()){
        context.write(new Text(entry.getKey()),new IntWritable(entry.getValue()));
        }


   }
  public Map<String , Integer > sortMap (Map<String,Integer> unsortMap){

    Map<String ,Integer> hashmap = new HashMap<String,Integer>();
    int count=0;
    List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
    //Sorting the list we created from unsorted Map
    Collections.sort(list , new Comparator<Map.Entry<String,Integer>>(){

        public int compare (Map.Entry<String , Integer> o1 , Map.Entry<String , Integer> o2 ){
            //sorting in descending order
            return o2.getValue().compareTo(o1.getValue());

        }


    });

    for(Map.Entry<String, Integer> entry : list){
        // only writing top 3 in the sorted map 
        if(count>2)
            break;

        hashmap.put(entry.getKey(),entry.getValue());


    }

    return hashmap ;

    }

  }

希望这会有所帮助。