gpt4 book ai didi

sorting - MapReduce按值降序排序

转载 作者:行者123 更新时间:2023-12-02 19:57:56 25 4
gpt4 key购买 nike

我正在尝试用伪代码编写一个MapReduce任务,该任务返回以降序排序的项目。例如:对于wordcount任务,而不是:

apple 1
banana 3
mango 2

我希望输出为:
banana 3
mango 2
apple 1

关于如何做的任何想法?我知道如何以升序(在映射器作业中替换键和值)而不是以降序进行。

最佳答案

在这里,您可以利用以下reducer代码的帮助来实现降序排序。
假设您已经编写了映射器和驱动程序代码,其中映射器将生成输出为(Banana,1)等
在reducer中,我们将求和特定键的所有值,并将最终结果放入映射中,然后根据值对映射进行排序,并将最终结果写入reduce的清除函数中。
请参阅以下代码,进一步了解情况:

public class Word_Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {
// Change access modifier as per your need
public Map<String , Integer > map = new LinkedHashMap<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" associated with each word
}
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 LinkedHashMap<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 ;
}

关于sorting - MapReduce按值降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com