flink中滚动聚合算子-max和maxBy的区别

这段代码展示了如何在Java中使用Stream API的maxBy方法获取每个SensorReading对象按temperature属性的最大值,与直接使用max进行比较。maxBy返回最大值及其所在对象,而max则替换最大值位置的原始对象。理解两者行为有助于优化数据处理过程。
摘要由CSDN通过智能技术生成

代码

public class Test2_RollingAggregation {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        executionEnvironment.setParallelism(1);
        DataStream<SensorReading> dataStream = executionEnvironment.fromCollection(Arrays.asList(
                new SensorReading("sensor_1", 1547718199L, 35.8),
                new SensorReading("sensor_6", 1547718201L, 15.4),
                new SensorReading("sensor_7", 1547718202L, 6.7),
                new SensorReading("sensor_6", 1547718203L, 15.9),
                new SensorReading("sensor_10", 1547718205L, 38.1),
                new SensorReading("sensor_6", 1547718206L, 15.1),
                new SensorReading("sensor_6", 1547718209L, 15.0)
        ));
        KeyedStream<SensorReading, Tuple> keyedStream = dataStream.keyBy("id");
        SingleOutputStreamOperator<SensorReading> temperature = keyedStream.maxBy("temperature");
        temperature.print();
        executionEnvironment.execute();
    }
}

输出:

SensorReading{id='sensor_1', timestamp=1547718199, temperature=35.8}
SensorReading{id='sensor_6', timestamp=1547718201, temperature=15.4}
SensorReading{id='sensor_7', timestamp=1547718202, temperature=6.7}
SensorReading{id='sensor_6', timestamp=1547718203, temperature=15.9}
SensorReading{id='sensor_10', timestamp=1547718205, temperature=38.1}
SensorReading{id='sensor_6', timestamp=1547718203, temperature=15.9}
SensorReading{id='sensor_6', timestamp=1547718203, temperature=15.9}

如将上述代码改为:

        SingleOutputStreamOperator<SensorReading> temperature = keyedStream.maxBy("temperature");

输出:

SensorReading{id='sensor_1', timestamp=1547718199, temperature=35.8}
SensorReading{id='sensor_6', timestamp=1547718201, temperature=15.4}
SensorReading{id='sensor_7', timestamp=1547718202, temperature=6.7}
SensorReading{id='sensor_6', timestamp=1547718201, temperature=15.9}
SensorReading{id='sensor_10', timestamp=1547718205, temperature=38.1}
SensorReading{id='sensor_6', timestamp=1547718201, temperature=15.9}
SensorReading{id='sensor_6', timestamp=1547718201, temperature=15.9}

总结:maxBy会输出最大值所在的javaBean,而max不会输出最大值所在的JavaBean,而是直接替换第一次出现的对应位置上面的值。同理,min和mixBy也是这个道理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值