使用流获取字符串数组的 int 数组

问题描述 投票:0回答:3

给定一个字符串数组,我想计算每个字符串中“1”字符的数量。

示例:

Input: ["00101010", "10010", "11111"]  
Output: [3, 2, 5]
String []b = ["00101010", "10010", "11111"];
int [] c = Arrays.stream(b).mapToInt(r -> countChar(r, '1')).toArray();

int countChar(String string, char x) {
    return (int)string.chars().filter(ch -> ch == x).count();
}

我怎样才能在一个声明中写下这个?

我尝试用

countChar(r, '1')
和各种组合替换
(int)string.chars().filter(ch -> ch == x).count()
。错误日志太大了,我无法理解。

java java-stream
3个回答
3
投票

您可以将

countChar(r, '1')
方法调用替换为方法体:

int[] c = Arrays.stream(b)
                .mapToInt(r -> (int) r.chars()
                                      .filter(ch -> ch == '1')
                                      .count())
                .toArray();

1
投票

如果你所有的字符都是 0 和 1,那么这样的东西应该可以工作。去掉所有的0,字符串的长度就是1的个数。这不是最有效的方法,因为替换方法会创建一个一次性字符串。

.stream()
.map(s -> s.replace("0", ""))
.mapToInt(String::length)
.toArray();

如果有其他字符,您可以创建一个正则表达式来替换除空字符串之外的所有字符。


0
投票

代码点和并行编程

其他答案都很好。但是 (a),我建议在处理单个字符时养成使用 code point 整数的习惯,而不是使用

char
类型。 (b),您在评论中提到您想要并行编程。

数字

1
的代码点是49。

    int[] counts =
        Stream
        .of(  new String[] { "00101010", "10010", "11111" } )
        .parallel()
        .mapToInt( ( String s ) -> Math.toIntExact( s.codePoints().filter( (int codePoint) -> codePoint == 49 ).count() ) )
        .toArray() ;

请注意,并行并不一定意味着更快

查看此代码在 Ideone.com 上运行

© www.soinside.com 2019 - 2024. All rights reserved.