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!
Leave a Reply