Is there an equivalent of Javascript's Array.map
in Java?
I have been playing with Java 8 :
List<Long> roleList = siteServiceList.stream()
.map(s -> s.getRoleIdList()).collect(Collectors.toList());
but this doesn't work I don't know why the warning says Incompatible Type
.
How can I do this in Java8?
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another.
map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
map() is a functional programming technique. It iterates through the elements of an array, transforms each member of that array, and returns a new array of the same size with the transformed members e.g. performing calculations on a list of numbers. It does not mutate the original data, it returns a new array.
If roleIdList
is a List<Long>
and you want to get a List<Long>
you have to use flatMap
instead :
List<Long> roleList = siteServiceList.stream()
.flatMap(s -> s.getRoleIdList().stream())
.collect(Collectors.toList());
If you insist using map
the return type should be List<List<Long>>
:
List<List<Long>> roleList = siteServiceList.stream()
.map(MyObject::getRoleIdList)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With