简体   繁体   English

替换 ArrayList 中的字符串

[英]Replace string in ArrayList

I am string to replace a string in a column ArrayList.我是字符串来替换列 ArrayList 中的字符串。 I am getting an error on the expression我在表达式上遇到错误

Bad return type in lambda expression: String cannot be converted to Articles

articlesArrayList.replaceAll(articles -> articles.getAuthor().replace("."," "));

The replaceAll method is trying to return an array of articles. replaceAll方法试图返回一组文章。 Your function map is returning a string instead.您的函数映射返回的是一个字符串。 If you want to replace the '.'如果你想替换'.' character with ' ' for each author, use the ArrayList.forEach method instead.每个作者都带有 ' ' 的字符,请改用ArrayList.forEach方法。

class Main {
    public static void main(String[] args) {
        new Main().replace();
    }

    public void replace() {
        List<Article> articlesArrayList = new ArrayList<>();
        articlesArrayList.add(Article.builder().author("Sagar.Gangwal").build());
        articlesArrayList.stream().forEach(article -> article.getAuthor().replaceAll(".", " "));

        articlesArrayList = articlesArrayList.stream()
                .map(a -> this.update(a)).collect(Collectors.toList());
        System.out.println(articlesArrayList.get(0));
    }

    private static Article update(Article a) {
        a.author = a.getAuthor().replaceAll("\\.", " ");
        return a;
    }
}

You can see above code.你可以看到上面的代码。

Here i am trying to create stream and then foreach element of that stream i want to update AuthorName with '.'在这里,我试图创建流,然后 foreach 流的元素,我想用 '.' 更新 AuthorName。 to space.到空间。

articlesArrayList.stream().map(a -> this.update(a)).collect(Collectors.toList());

You need to use stream API and then custom update method to update value.您需要使用流 API,然后使用自定义更新方法来更新值。

Also for replacing '.'也用于替换'.' , you need to use escape character as well. ,您还需要使用转义字符。 replaceAll method of String class contains first argument as regular expression . String类的replaceAll方法包含第一个参数作为regular expression

If you see this , i am escaping '.'如果你看到这个,我正在逃避'.' with '\\\\.''\\\\.' . . a.getAuthor().replaceAll("\\\\.", " ");

So instead of replaceAll , you can go with replace method which simply take first argument as simply replace one character with passed target character.因此,代替replaceAll ,您可以使用 replace 方法,该方法只需将第一个参数作为简单地用传递的目标字符替换一个字符即可。

You can see difference between replace and replaceAll.您可以看到replace and replaceAll.之间的区别replace and replaceAll.

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

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