Java 8 Stream数组中的唯一字符 [英] Java 8 Stream unique characters from array

查看:102
本文介绍了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,然后是mapdistinct,最后是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.

推荐答案

您需要使用

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数组中的唯一字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆