如何从流中删除数字和空格?

时间:2019-05-14 09:47:26

标签: java arrays filter java-stream

我试图将args转换为流。然后必须将流设置为大写,从字符串(而不是整个字符串)中删除数字和空格。 创建流和大写字母成功完成了工作,现在我陷入了过滤方法的困境,我不明白为什么我的代码无法正常工作,已经做了一些研究。

package A_11;

import java.util.Arrays;
import java.util.stream.Stream;

public class A_11_g {
    public static void main(String[] args){
        Stream<String> stream = Arrays.stream(args);
        stream.map(s -> s.toUpperCase()).filter(s -> Character.isDigit(s)).filter(e -> !e.isEmpty())
                .forEach(name -> System.out.print(name + " "));
    }
}

2 个答案:

答案 0 :(得分:1)

filter()产生一个新的流,其中包含满足谓词(您提供的条件)的原始元素。 您想要的是map()函数,该函数在将给定函数应用于原始流的每个元素之后会生成一个新流。

下面的方法应该可以解决问题,在底部有一些断言,您可以选择使用它们在单元测试中进行验证。

Stream<String> stringStream = Stream.of("unfiltered", "withDigit123", " white space ");

List<String> filtered = stringStream.map(s -> s.toUpperCase())//Can be replaced with .map(String::toUpperCase) if you want, but did it this way to make it easier to understand for someone new to all this.
        .map(s -> s.replaceAll("[0-9]", ""))//Removes all digits
        .map(s -> s.replace(" ", ""))//Removes all whitespace
        .collect(Collectors.toList());//Returns the stream as a list you can use later, technically not what you asked for so you can change or remove this depending on what you want the output to be returned as.

//Assertions, optional.
assertTrue(filtered.contains("UNFILTERED"));
assertTrue(filtered.contains("WITHDIGIT"));
assertTrue(filtered.contains("WHITESPACE"));

答案 1 :(得分:0)

如果您真的真的想使用流来执行此操作,则需要在较低级别上应用过滤逻辑-不在字符串流上,而是在单个字符串内的字符流上应用过滤逻辑:

System.out.println(
    "abcd 123 efgh".chars()
        .map(Character::toUpperCase)
        .filter(c -> !Character.isDigit(c))
        .filter(c -> !Character.isSpaceChar(c))
        .mapToObj(c -> String.valueOf((char) c))
        .collect(Collectors.joining())
);
  

ABCDEFGH

mapToObj部分是为了避免必须处理自定义收集器,否则它是必需的,因为该流是IntStream而不是常规的对象流。)

如果需要,您可以将其包装到处理多个字符串的流中-然后,上述逻辑将放在该流的map操作内。