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.
java java-stream
add a comment |
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.
java java-stream
add a comment |
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.
java java-stream
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.
java java-stream
java java-stream
edited Nov 16 '18 at 11:51
Stefan Zobel
2,48231931
2,48231931
asked Nov 16 '18 at 7:25
elpelp
364116
364116
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
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.
add a comment |
Stream the List
, map
it to your target type and collect
to a List
:
List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());
add a comment |
Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.
According to JavaDoc Collecotrs.toList
Returns a
Collector
that accumulates the input elements into a new
List
. There are no guarantees on the type, mutability,
serializability, or thread-safety of theList
returned; if more
control over the returnedList
is required, use
toCollection(Supplier)
.
The returned articles
are of type ArrayList<ArticleEntity>
. Thus this list is e.g. mutable.
The return type of the method getAllArticle()
is Iterable<Article>
. Thus we can call
Iterator<Article> iterator = getAllArticle().iterator();
But if you need to call iterator.remove()
"there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)
UnsupportedOperationException - if the remove operation is not
supported by this iterator
To keep the behaviour of the original code use Collectors.toCollection
:
List<Article> articles = articleEntities.stream()
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toCollection(Lists::newArrayList));
This will return articles
built by Lists.newArrayList()
.
add a comment |
As Iterable
is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport
you can generate a stream
from the Iterable
instance and reduce the amount of operations to one:
final List<Article> articlesList =
StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toList());
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333221%2fbeautify-for-loop-using-stream-and-lambda%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
add a comment |
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.
add a comment |
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.
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.
edited Nov 16 '18 at 20:02
Aomine
42.5k74676
42.5k74676
answered Nov 16 '18 at 7:28
SweeperSweeper
71.1k1075144
71.1k1075144
add a comment |
add a comment |
Stream the List
, map
it to your target type and collect
to a List
:
List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());
add a comment |
Stream the List
, map
it to your target type and collect
to a List
:
List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());
add a comment |
Stream the List
, map
it to your target type and collect
to a List
:
List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());
Stream the List
, map
it to your target type and collect
to a List
:
List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());
answered Nov 16 '18 at 7:28
EranEran
290k37477563
290k37477563
add a comment |
add a comment |
Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.
According to JavaDoc Collecotrs.toList
Returns a
Collector
that accumulates the input elements into a new
List
. There are no guarantees on the type, mutability,
serializability, or thread-safety of theList
returned; if more
control over the returnedList
is required, use
toCollection(Supplier)
.
The returned articles
are of type ArrayList<ArticleEntity>
. Thus this list is e.g. mutable.
The return type of the method getAllArticle()
is Iterable<Article>
. Thus we can call
Iterator<Article> iterator = getAllArticle().iterator();
But if you need to call iterator.remove()
"there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)
UnsupportedOperationException - if the remove operation is not
supported by this iterator
To keep the behaviour of the original code use Collectors.toCollection
:
List<Article> articles = articleEntities.stream()
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toCollection(Lists::newArrayList));
This will return articles
built by Lists.newArrayList()
.
add a comment |
Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.
According to JavaDoc Collecotrs.toList
Returns a
Collector
that accumulates the input elements into a new
List
. There are no guarantees on the type, mutability,
serializability, or thread-safety of theList
returned; if more
control over the returnedList
is required, use
toCollection(Supplier)
.
The returned articles
are of type ArrayList<ArticleEntity>
. Thus this list is e.g. mutable.
The return type of the method getAllArticle()
is Iterable<Article>
. Thus we can call
Iterator<Article> iterator = getAllArticle().iterator();
But if you need to call iterator.remove()
"there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)
UnsupportedOperationException - if the remove operation is not
supported by this iterator
To keep the behaviour of the original code use Collectors.toCollection
:
List<Article> articles = articleEntities.stream()
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toCollection(Lists::newArrayList));
This will return articles
built by Lists.newArrayList()
.
add a comment |
Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.
According to JavaDoc Collecotrs.toList
Returns a
Collector
that accumulates the input elements into a new
List
. There are no guarantees on the type, mutability,
serializability, or thread-safety of theList
returned; if more
control over the returnedList
is required, use
toCollection(Supplier)
.
The returned articles
are of type ArrayList<ArticleEntity>
. Thus this list is e.g. mutable.
The return type of the method getAllArticle()
is Iterable<Article>
. Thus we can call
Iterator<Article> iterator = getAllArticle().iterator();
But if you need to call iterator.remove()
"there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)
UnsupportedOperationException - if the remove operation is not
supported by this iterator
To keep the behaviour of the original code use Collectors.toCollection
:
List<Article> articles = articleEntities.stream()
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toCollection(Lists::newArrayList));
This will return articles
built by Lists.newArrayList()
.
Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.
According to JavaDoc Collecotrs.toList
Returns a
Collector
that accumulates the input elements into a new
List
. There are no guarantees on the type, mutability,
serializability, or thread-safety of theList
returned; if more
control over the returnedList
is required, use
toCollection(Supplier)
.
The returned articles
are of type ArrayList<ArticleEntity>
. Thus this list is e.g. mutable.
The return type of the method getAllArticle()
is Iterable<Article>
. Thus we can call
Iterator<Article> iterator = getAllArticle().iterator();
But if you need to call iterator.remove()
"there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)
UnsupportedOperationException - if the remove operation is not
supported by this iterator
To keep the behaviour of the original code use Collectors.toCollection
:
List<Article> articles = articleEntities.stream()
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toCollection(Lists::newArrayList));
This will return articles
built by Lists.newArrayList()
.
edited Nov 16 '18 at 13:37
answered Nov 16 '18 at 8:25
LuCioLuCio
2,8921924
2,8921924
add a comment |
add a comment |
As Iterable
is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport
you can generate a stream
from the Iterable
instance and reduce the amount of operations to one:
final List<Article> articlesList =
StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toList());
add a comment |
As Iterable
is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport
you can generate a stream
from the Iterable
instance and reduce the amount of operations to one:
final List<Article> articlesList =
StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toList());
add a comment |
As Iterable
is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport
you can generate a stream
from the Iterable
instance and reduce the amount of operations to one:
final List<Article> articlesList =
StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toList());
As Iterable
is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport
you can generate a stream
from the Iterable
instance and reduce the amount of operations to one:
final List<Article> articlesList =
StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
.map(ArticleMapper::articleEntity2Article)
.collect(Collectors.toList());
edited Nov 16 '18 at 8:10
answered Nov 16 '18 at 8:04
BradBrad
1739
1739
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333221%2fbeautify-for-loop-using-stream-and-lambda%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown