Home > Mobile >  How to use stream in Java
How to use stream in Java

Time:05-20

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));
    }

CodePudding user response:

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>

  •  Tags:  
  • java
  • Related