用于计算唯一对象的 Java lambda 表达式

我已经在下面设置了这个流,并且不能在 .map 上使用方法 count()。仅在过滤器上。但我没有设置任何过滤条件。我怎么能在下面这个流的字符串数组上做到这一点?

我想根据 replaceAll 中的正则表达式对字符串进行排序,并获取唯一字符串并获取唯一字符串的总数。

Stream newStream = Arrays.stream(arr)
                    .map(s -> s.replaceAll("[^a-z]", ""))
                    .distinct()


慕尼黑5688855
浏览 160回答 3
3回答

繁花不似锦

如果要计算distinct字符串的数量,可以这样做:long countDistinct = Arrays.stream(arr)         .map(s -> s.replaceAll("[^a-z]", ""))         .distinct() // intermediate operation with unique strings as 'Stream' return type         .count();   // terminal operation with count of such strings as return type

慕娘9325324

我不确定我是否完全理解您的要求。List在将正则表达式应用于数组的每个元素之后,您似乎想要对不同的字符串进行排序。这List将同时具有元素及其计数:List<String>&nbsp;list&nbsp;=&nbsp;Arrays.stream(arr) &nbsp;&nbsp;&nbsp;&nbsp;.map(s&nbsp;->&nbsp;s.replaceAll("[^a-z]",&nbsp;"")) &nbsp;&nbsp;&nbsp;&nbsp;.distinct() &nbsp;&nbsp;&nbsp;&nbsp;.sorted() &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());现在,list持有元素。如果您还想知道它包含多少元素,只需使用以下List.size方法:int&nbsp;count&nbsp;=&nbsp;list.size();编辑:如果您还需要Stream更改字符串、唯一和排序的字符串,只需创建一个新Stream的 from&nbsp;list:Stream<String>&nbsp;newStream&nbsp;=&nbsp;list.stream();

幕布斯6054654

以列表形式收集和获取总数都是终端操作,因此您只能在实时流中执行任一操作。如果您必须使用相同的流来获取字符串列表和计数,一个(hacky)选项是使用Supplier<Stream<T>>:String text = "FOO bar BAZ TEXT text some";String[] arr = text.split(" ");Supplier<Stream<String>> sameStream = () -> Arrays.stream(arr)&nbsp; &nbsp; &nbsp; &nbsp; .map(s -> s.replaceAll("[^a-z]", ""))&nbsp; &nbsp; &nbsp; &nbsp; .distinct()&nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> !s.isEmpty())&nbsp; &nbsp; &nbsp; &nbsp; .sorted();System.out.println("Unique strings are: " + sameStream.get().collect(Collectors.toList()));System.out.println("Count of Unique strings are: " + sameStream.get().count());上面产生了这个输出:Unique strings are: [bar, some, text]Count of Unique strings are: 3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java