java变量不能传递到for循环中

r1zhe5dt  于 2021-05-27  发布在  Hadoop
关注(0)|答案(1)|浏览(379)

我有一个Dataframe,包括发送方(id,int)、接收方(id,int)、通信时间(int)。

A B C
1 5 10
1 6 20
1 7 20
1 8 11

我的目标是找到最大通信次数并返回16,20(格式为a b,c),因为a1,b6和a1,b7都有最大通信次数20,我只需要保留最小的b id号。
在Map步骤中,我已经将a分隔为键,(b,c)分隔为值。
到目前为止,我可以用a和max c返回输出,但是我很难返回b值。我下面的代码无法更改min\ u接收器,如何解决此问题?

public static class IntSumReducer
extends Reducer<Text,Text,Text,Text> {
    //private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<Text> values,
                       Context context
                       ) throws IOException, InterruptedException {
        int max_val = 0;
    int val_str = 0;
    int val_str_1 = 0;
    int min_Receiver = Integer.MAX_VALUE;
    int tempReceiver = 0;
        for (Text val : values) {
    String[] compositeString = val.toString().split(",");
    val_str = Integer.parseInt(compositeString[1]);
    //tempReceiver = Integer.parseInt(compositeString[0]);
            if( val_str>max_val) {
                max_val = val_str;

    }

    }

   for (Text val_1 : values){
    String[] compositeString = val_1.toString().split(",");
    tempReceiver = Integer.parseInt(compositeString[0]);        
    val_str_1 = Integer.parseInt(compositeString[1]);

    if (val_str_1 == max_val && tempReceiver < min_Receiver)
        {
           min_Receiver =tempReceiver;
        }

    }

        //result.set(max_val);
        context.write(key, new Text(min_Receiver + "," + max_val));}}

预期输出为

1 6,20

实际输出为

1 2147483647,20

在Map中,我已经将a作为键,b,c作为值。所以复合字符串包含两个变量。值的格式是b,c。

ux6nzvsh

ux6nzvsh1#

取决于你的delimeter是什么
用这样一条线来得到 Text 用最长的时间

Optional<Text> answer = StreamSupport.stream(values.spliterator(),false)  //all this does is get you a stream of Text
.max(Comparator.comparingInt(s->getComTime(s))); // return the object that evaluates to the max value if one exists

同时创建一个从字符串/文本获取通信时间的方法,如下所示:

private static int getComTime(Text line){
    String[] vals = line.toString().split(",");
    return  Integer.parseInt(vals[2]);
}

.stream()的布尔选项是= false 或平行= true .... 如果分隔符不同或对象稍有不同,则可能需要进行调整 getComTime 但这应该很接近右边。
如果你想用这种方式处理的话,可以选择一个。
那你就可以了

if(answer.isPresent()){/* got an answer do something with it */}

***sry我用字符串而不是文本做了大部分这件事,但这是更新让我知道如果有任何问题。

相关问题