在 Flink 中获取传入字符串流,并将其放入数组中,可以通过以下步骤实现:
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> input = env.fromElements("Hello", "World", "Flink", "Stream", "Array");
DataStream<String[]> result = input.flatMap(new FlatMapFunction<String, String[]>() {
@Override
public void flatMap(String value, Collector<String[]> out) {
String[] array = value.split(" "); // 使用空格分割字符串
out.collect(array);
}
});
result.print();
完整的示例代码如下:
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
public class FlinkStringArrayExample {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> input = env.fromElements("Hello", "World", "Flink", "Stream", "Array");
DataStream<String[]> result = input.flatMap(new FlatMapFunction<String, String[]>() {
@Override
public void flatMap(String value, Collector<String[]> out) {
String[] array = value.split(" ");
out.collect(array);
}
});
result.print();
env.execute("Flink String Array Example");
}
}
这个例子中,我们创建了一个字符串流,并使用 flatMap
函数将每个字符串按空格分割为数组。最后,我们打印出结果。你可以根据实际需求对结果进行进一步处理或使用其他 Flink 的操作符。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体的产品选择应根据实际需求和情况进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云