How to transform all items in a List
or Array
to another array? If you come from JavaScript world mean map
method, in .Net, you would use LINQ
and Select
method.
But how is that in Java 8?
The answer is quite easy, if you find the Stream API of Java 8. These API supports functional-style operations on streams of elements, such as map-reduce transformations on collections.
So in Javascript the code would be like:
const transformedCtas = section.elements.cta.value.map(cta => ({
ctaTitle: cta.elements.title.value,
ctaUrl: cta.elements.external_url.value
}));
In Java 8, you would use:
List<CTA> transfomedCtas = section
.getElements()
.getCta() // This returns List/Enumerable/...
.stream() // This is the key - transform data to sream and then use strem API for whatever you want
.map(cta ->
new CTA(cta.getElements().getTitle(), cta.getElements().getExternalUrl()
);