Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of Javascript's Array.map in Java 8?

Tags:

java

java-8

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?

like image 978
Dimitri Kopriwa Avatar asked Nov 26 '17 10:11

Dimitri Kopriwa


People also ask

What is map function in Java 8?

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.

Can we use map on array?

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.

What does the map ()` array method do?

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Does map mutate 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.


1 Answers

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());
like image 135
YCF_L Avatar answered Sep 18 '22 20:09

YCF_L