简体   繁体   中英

Replace string in ArrayList

I am string to replace a string in a column 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. 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.

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 '.' 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.

Also for replacing '.' , you need to use escape character as well. replaceAll method of String class contains first argument as 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.

You can see difference between replace and replaceAll.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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