Java 8 Stream数组中的唯一字符

编程入门 行业动态 更新时间:2024-10-27 02:25:11
本文介绍了Java 8 Stream数组中的唯一字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尝试编写一个简单的程序,该程序将在 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数组中的唯一字符

本文发布于:2023-11-30 18:01:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   字符   Java   Stream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!