尝试编写一个简单的程序,该程序将在 Java8 中从输入数组中打印出唯一的单词.例如,如果输入为
Trying to write a simple program that will print the unique words from an input array in Java8 . For example if the input is
String[] input = {"This", "is", "This", "not"};程序应输出[T, h, i, s, n, o, t],元素的顺序应与输入中出现的顺序相同.我的方法是先输入split,然后是map,distinct,最后是collect到列表.但是下面的代码是打印流而不是单词的列表,我想念的是什么?例如.
The program should output [T, h, i, s, n, o, t] , the order of elements should follow the same pattern as they appear in input. My approach is to split the input , then map, distinct and finally collect it toList. But the following code is printing list of streams instead of words, what am i missing?.E.g.
String[] input = {"This", "is", "This", "not"}; System.out.println(Arrays.stream(input) .map(word -> word.split("")) .map(Arrays::stream) .distinct() .collect(toList()));当前输出
[java.util.stream.ReferencePipeline$Head@548c4f57, java.util.stream.ReferencePipeline$Head@1218025c, java.util.stream.ReferencePipeline$Head@816f27d, java.util.stream.ReferencePipeline$Head@87aac27]我很想看看Java8中是否还有其他方法可以达到相同的目的.
I am interested to see if there are some other ways in Java8 to achieve the same.
推荐答案您需要使用 flatMap 以便与流的内容进行映射.正如您所注意到的,Arrays::stream生成单独的流,而您想要的是将所有这些流展平为单个流,例如.
You need to use flatMap in order to map with the content of the stream . As you noticed that Arrays::stream generate separate streams and what you want is to flatten all those streams into single stream E.g.
System.out.println(Stream.of(input) .map(w -> w.split("")) .flatMap(Arrays::stream) .distinct() .collect(Collectors.toList()));输出
[T, h, i, s, n, o, t]更多推荐
Java 8 Stream数组中的唯一字符
发布评论