Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use stream in Java

I have a list of users that need to be sorted by the first name. How do I use stream correctly in this situation?

public static List<User> users= List.of(
    new User("Andrea", "Winter", 45),
    new User("Lucy", "Diamond",  24));

static List<String> firstName() {

 return  users.stream()
                .sorted(Comparator.comparing(User::FirstName));
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You were close. You just didn’t return a list.

return  users.stream().sorted(Comparator.comparing(User::FirstName))
      .toList();

or

return  users.stream().sorted(Comparator.comparing(User::FirstName))
          .collect(Collectors.toList());

If this is not within a method of return type List<User> then just assign the result to List<User>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading