Fold算子:将数据流的每一次输出进行滚动叠加,合并输出结果
示例环境
java.version: 1.8.x
flink.version: 1.11.1
示例数据源(项目码云下载)
Fold.java
import com.flink.examples.DataSource;
import org.apache.flink.api.common.functions.FoldFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.List;
/**
* @Description Fold算子:将数据流的每一次输出进行滚动叠加,合并输出结果
* (与Reduce的区别是,Reduce是拿前一次聚合结果累加后一次的并输出数据流;Fold是直接将当前数据对象追加到前一次叠加结果上并输出数据流)
*/
public class Fold {
/**
* 遍历集合,分区打印每一次滚动叠加的结果(示例:按性别分区,按排序,未位追加输出)
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(4);
List<Tuple3<String,String,Integer>> tuple3List = DataSource.getTuple3ToList();
//注意:使用Integer进行分区时,会导致分区结果不对,转换成String类型输出key即可正确输出
KeyedStream<Tuple3<String,String,Integer>, String> keyedStream = env.fromCollection(tuple3List).keyBy(new KeySelector<Tuple3<String,String,Integer>, String>() {
@Override
public String getKey(Tuple3<String, String, Integer> tuple3) throws Exception {
//f1为性别字段,以相同f1值(性别)进行分区
return String.valueOf(tuple3.f1);
}
});
SingleOutputStreamOperator<String> result = keyedStream.fold("同学:", new FoldFunction<Tuple3<String, String, Integer>, String>() {
@Override
public String fold(String s, Tuple3<String, String, Integer> tuple3) throws Exception {
if (s.startsWith("男") || s.startsWith("女")){
return s + tuple3.f0 + "、";
} else {
return (tuple3.f1.equals("man") ? "男" : "女") + s + tuple3.f0 + "、";
}
}
});
result.print();
env.execute("flink Fold job");
}
}
打印结果
2> 男同学:张三、
2> 男同学:张三、王五、
2> 男同学:张三、王五、吴八、
1> 女同学:李四、
1> 女同学:李四、刘六、
1> 女同学:李四、刘六、伍七、