Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beautify for loop using stream and lambda

Currently I got this code:

@GetMapping("/all/")
    public Iterable<Article> getAllArticle(){
        ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
        ArrayList<Article> articles = Lists.newArrayList();
        for(ArticleEntity articleEntity : articleEntities){
            articles.add(ArticleMapper.articleEntity2Article(articleEntity));
        }
        return articles;
    }

The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.

I tried using something like list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.

like image 273
elp Avatar asked Dec 11 '22 04:12

elp


1 Answers

A simple map will do the job:

List<Article> articles = articleEntities.stream()
                                        .map(ArticleMapper::articleEntity2Article)
                                        .collect(Collectors.toList());

map converts each element to something else using the method given.

like image 94
Sweeper Avatar answered Dec 21 '22 17:12

Sweeper