0

I am converting my project to java8. How would I write this code in a better way using java8?

List<Bar> bars = new ArrayList<>();
for (Foo foo : obj.getFooList()) {
    bars.add(Helper.fooToBar(foo));
}
return detailsVos;
1
  • Whether it is to make a List<Bar> out of a List<Foo> by invoking a method, or List<Integer> out of a List<String>, the answer is the same, and you can refer to the linked question. Note that, since you're clearly learning the Stream API, you'll likely understand more by reading the stream tutorial, and then reading any answers. Commented Nov 28, 2016 at 12:36

1 Answer 1

2

Stream the list, mapping using a method reference, then collect to a list and return it:

return obj.getFooList().stream().map(Helper::fooToBar).collect(Collectors.toList());

Note that "better" has been interpreted as "neater" and "using the Java 8 style".

Also note that this may perform slightly worse than your original code, due to the overhead of using a stream.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think it'll perform worse. Not in the general case, or not in a measurable way; if it were so important, there would be no reason to use Stream to begin with.
Most experienced “overhead of using a stream” stems from the fact that when Streams aren’t used anywhere else, their initial overhead adds to your operation. If they were used as much as the Collection API, there was never any noticeable overhead. Like no-one notices the Iterator overhead when using a for-each loop…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.