Sort a List of Objects by Multiple Fields

Situation:
You need to sort a list of users first by their ID and then by their name.

Solution:

List<User> users = Arrays.asList(new User(2, "Charlie"), new User(1, "Alice"), new User(1, "Bob"));

List<User> sortedUsers = users.stream()
    .sorted(Comparator.comparing(User::getId).thenComparing(User::getName))
    .collect(Collectors.toList());

System.out.println(sortedUsers);

Explanation:
This code sorts users by ID first, and if IDs are the same, it then sorts them by name.

Result:

[User{id=1, name='Alice'}, User{id=1, name='Bob'}, User{id=2, name='Charlie'}]

Sorted to perfection! You’ve organized your data like a pro. Keep up the great work!


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect