繁体   English   中英

使用 Java 中的 stream 对字符串中的所有字母进行计数/排序(忽略数字)

[英]Count/sort all letters in a string with a stream in Java (ignoring numbers)

我的朋友说这是不可能的,但我相信她错了。 假设我有一个由字母数字字符组成的字符串列表:

"aa1, aaaa, aaa, a12, a5, 44a44, 3232aa"

我想写一个 stream 将:

  • 查看每个单独的元素
  • 识别计数所有字母(忽略数字)
  • 如果数字是奇数,做 x
  • 如果数字是偶数,做 y

她说这将导致 stream(计数)内的终端操作,这是不可能的。 我在网上看了看,开始后,我的想法是过滤掉所有偶数会更容易。 我最终得到了这个:

List<String> evaluateStrings = validChars.stream().filter(x -> x.replaceAll("\\d","").length() %2 == 0).collect(Collectors.toList());

但这甚至不能过滤掉所有的数字。

对此有什么想法吗?

尝试使用 map function 删除数字。

我强烈建议在 map 之前进行过滤以检查 null 字符串,否则您可能会以某种方式得到 null 指针异常 (NPE)。 在使用流和转换数据时,我非常强调过滤掉 null 值,当您开始从不同来源流式传输不同数据类型时,它将为您节省很多麻烦。

List<String> evaluateStrings = validChars.stream()
// transform the data in the stream, remove numeric chars
.map(x -> x.replaceAll("\\d",""))
// Filter to allow even length strings
.filter(x -> x.length() %2 == 0)
// Collect the transformed and filtered results.
.collect(Collectors.toList());

如果您想将所有字符串收集到一个集合中,同时执行 x 以及为什么取决于偶数或奇数:

List<String> evaluateStrings = validChars.stream()
// transform the data in the stream, remove numeric chars
.map(x -> x.replaceAll("\\d","")
// Filter to allow even length strings
.map(x -> {
      if(x.length() %2 == 0) {
        //if number is even, do x
        return doY(x);
      } else {
        // If number is odd, do y
        return doX(x);
      }
})
// Collect the transformed and filtered results.
.collect(Collectors.toList());

是的,可能

我的朋友说这是不可能的,但我相信她错了

是的,她错了。 您可以使用流在一行代码中完成所有这些。

代码点

避免 Java 中的char / Character类型,因为它自 Java 2 以来基本上已被破坏,以及自char 5 以来的遗留物。

你的问题不清楚。 我猜“do x”和“do y”的结果是你想要收集的字符串。

下面是一些示例代码。

Stream#map

在过滤掉表示数字或其他非字母字符的代码点后,我们使用Stream#map将输入的每个单词转换为其字母的计数。

我们使用三元运算符来调用偶数方法或奇数方法。 两种方法都返回一个String object。 我们将这些返回的String对象收集到一个列表中。

List < String > results = 
    Arrays
    .stream(
        "aa1, aaaa, aaa, a12, a5, 44a44, 3232aa"
        .split( ", " )
    )
    .map(
        string -> 
            string
            .codePoints()  // Returns an `IntStream`
            .filter( Character :: isAlphabetic ) // Eliminate digits, punctuation, etc.
            .count()      // Count how many alphabetic characters found in that word.
            % 2 == 0      // Use modulo to test for even number.
            ?             // Ternary operator. 
                doEven()  // returns a `String` object.
            : 
                doOdd()   // returns a `String` object.
    )
    .toList()
;

请参阅在 Ideone.com 上实时运行的代码

【偶、偶、奇、奇、奇、奇、偶】

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM