我已经在下面设置了这个流,但不能在 .map 上使用方法 count()。仅在过滤器上。但是我没有设置任何过滤条件。我怎样才能在下面这个流的字符串数组上做到这一点?
我想根据 replaceAll 中的正则表达式对字符串进行排序,并获取唯一字符串并获取唯一字符串总数。
Stream newStream = Arrays.stream(arr)
.map(s -> s.replaceAll("[^a-z]", ""))
.distinct()
最佳答案
如果您要计算 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
关于用于计算唯一对象的 Java lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54497313/