18

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?

2
  • 1
    Define "this doesn't work". Post all the relevant code, and the exact and complete error you get. Error messages are important. Commented Nov 26, 2017 at 10:45
  • Does it work with List<List<Long>> instead? Commented Nov 26, 2017 at 10:46

1 Answer 1

19

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.