基于flink使用对象封装实现worldcount

在上一篇博客:基于flink实现的worldcount通过Flink自带的Tuple实现了单词统计。需要注意Flink不是K,V格式的编程模型,我们可以对Flink使用非K,V格式编程来统计单词个数,这里可以使用一个对象的方式实现,本文在上一篇博客环境基础之上,通过封装对象实现。

1、创建WordDto

public class WordDto {
    private  String word;
    private  Integer count;
    public WordDto() {
    }
    public WordDto(String word, Integer count) {
        this.word = word;
        this.count = count;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    @Override
    public String toString() {
        return "word="+this.getWord()+",count="+this.getCount();
    }
}
FlinkWorldCount2 主类内容如下:
public class FlinkWorldCount2 {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env=ExecutionEnvironment.getExecutionEnvironment();
        DataSet<String>lines=env.readTextFile("./data/words");
        FlatMapOperator<String,String>words= lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                for (String word : value.split(" ")) {
                    out.collect(word);
                }
            }
        });
        MapOperator<String,WordDto>mapOperator=words.map(new MapFunction<String, WordDto>() {
            @Override
            public WordDto map(String word) throws Exception {
                return new WordDto(word,1);
            }
        });
        UnsortedGrouping<WordDto>grouping=mapOperator.groupBy("word");
        ReduceOperator<WordDto>reduce=grouping.reduce(new ReduceFunction<WordDto>() {
            @Override
            public WordDto reduce(WordDto w1, WordDto w2) throws Exception {
                return new WordDto(w1.getWord(),w1.getCount()+w2.getCount());
            }
        });
        reduce.print();
    }
}

通过封装对象实现flink算法时,需要注意以下几点:

  • 1 类的访问级别必须是public
  • 2.类中必须实现无参对象
  • 3.类中的属性必须是public或者private【必须实现getter /setter方法】
  • 4.类必须是可序列化的

程序运行结果如下
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜菜的中年程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值