如何拆分JavaDStream<String>并打印行的第二个单词。

huangapple go评论80阅读模式
英文:

How to split JavaDStream<String> and print the second word of the line

问题

在我分割行之后,我只能打印所有的单词,但在我的情况下,我只想要行中的第二个单词,我该如何解决呢?


JavaDStream<String> words = kafkaSparkInputDStream.flatMap(new FlatMapFunction<String, String>() {
                public Iterable<String> call(String x) {
                    return Arrays.asList(x.split(" "));
                }
            });
words.print();
英文:

after i split the line I can only print all the word, but in my case i want only the second word of the line how can i solve it?


JavaDStream&lt;String&gt; words = kafkaSparkInputDStream.flatMap(new FlatMapFunction&lt;String, String&gt;() {
                public Iterable&lt;String&gt; call(String x) {
                    return Arrays.asList(x.split(&quot; &quot;));
                }
            });
words.print();

答案1

得分: 0

You can choose which elements you want from the split array like this:

你可以选择从分割的数组中获取你想要的元素,就像这样:

JavaDStream<String> words = kafkaSparkInputDStream.flatMap(new FlatMapFunction<String, String>() {
    public Iterable<String> call(String x) {
        return Arrays.stream(x.split(" "))
            .skip(1)
            .limit(1)
            .collect(Collectors.toList());
    }
});
words.print();

请注意,代码部分不会被翻译。

英文:

Cant you just select which element's you want from splited array ? You can use
x.split(1)[1] but that one might result in exception's so another way of doing so which is more error prone is:

JavaDStream&lt;String&gt; words = kafkaSparkInputDStream.flatMap(new FlatMapFunction&lt;String, String&gt;() {
                public Iterable&lt;String&gt; call(String x) {
                    return Arrays.stream(x.split(&quot; &quot;))
                        .skip(1)
                        .limit(1)
                        .collect(Collectors.toList());
                }
            });
words.print();

huangapple
  • 本文由 发表于 2020年7月29日 07:33:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63144265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定