简体   繁体   English

从字符串的 ArrayList 中删除数字

[英]Remove numbers from ArrayList of Strings

I have ArrayList of Strings and I want to remove numbers from it.我有字符串的 ArrayList,我想从中删除数字。 How Can achieve it?怎样才能实现呢?

ArrayList<String> arraylist = new ArrayList();

arraylist.add("01 Hello 88");
arraylist.add("02 World 88");

For example I just want to remove 01 and 02 .. and rest can be same例如,我只想删除 01 和 02 .. 其余部分可以相同

Seems like you want subString only since you want to remove only 01 not 88 then you can use substring()似乎你只想要 subString 因为你只想删除01而不是88然后你可以使用substring()

for (int i = 0; i < arraylist.size(); i++) {
  arraylist.set(i, arraylist.get(i).substring(3));
}

Or You can use Stream API或者您可以使用 Stream API

List<String> arraylist = new ArrayList();
arraylist.add("01 Hello 88");
arraylist.add("02 World 88");
arraylist = arraylist.stream().map(a -> a.substring(3)).collect(Collectors.toList());

Interesting question.有趣的问题。 Here it is:这里是:

UnaryOperator<List<String>> trimHeader = (inList) -> {
    List<String> outList = new ArrayList<>();
    for (String s : inList) {
        String[] elements = s.split(" ");
        outList.add(Arrays.stream(elements).skip(1).collect(Collectors.joining(" ")));
    }
    return outList;
};

List<String> list = new ArrayList<>();
list.add("01 Hello 88");
list.add("02 World 88");
trimHeader.apply(list).forEach(System.out::println);

Output:输出:

Hello 88你好88
World 88世界88

Notice that the Lambda function brings no side-effect to the original list.请注意,Lambda 函数不会给原始列表带来任何副作用。

[Edit] Updated a variable name above. [编辑] 更新了上面的变量名称。 In addition, consider the function provided in this reply for a more general purpose usage -- it removes the first element based on checking the space.此外,请考虑此回复中提供的函数用于更通用的用途——它根据检查空间删除第一个元素。 The first element can be a number or some characters.第一个元素可以是数字或一些字符。

The easiest way to remove leading digits followed by spaces, is to use a regular expression to match that, and then replace it with an empty string.删除前导数字后跟空格的最简单方法是使用正则表达式进行匹配,然后将其替换为空字符串。

The regex would be ^\\d+\\s+ , which as a Java string literal would be "^\\\\d+\\\\s+" .正则表达式将是^\\d+\\s+ ,作为 Java 字符串文字将是"^\\\\d+\\\\s+"

To update all values in a list in Java 8+, you can do it using the replaceAll(UnaryOperator<E> operator) method, like this:要在 Java 8+ 中更新列表中的所有值,您可以使用replaceAll(UnaryOperator<E> operator)方法来完成,如下所示:

ArrayList<String> arraylist = new ArrayList<>();
arraylist.add("01 Hello 88");
arraylist.add("02 World 88");

arraylist.replaceAll(s -> s.replaceFirst("^\\d+\\s+", ""));

System.out.println(arraylist);

Output输出

[Hello 88, World 88]

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

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