0

If I have a list of an example class User (shown below), can I create a String array for all the names in the list with one line using lambda?

class User{
  String name;
  int id;
}
0

1 Answer 1

6

Yes. Given List<User> users:

String[] names = users.stream().map(user -> user.name).toArray(String[]::new);

That is "stream the users, get the name for each one, put them in a new String array."

If your User has a getName() method, then it would be:

String[] names = users.stream().map(User::getName).toArray(String[]::new);
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.