I have a list of User objects, defined as follows:
public class User {
private String userId; // Unique identifier
private String name;
private String surname;
private String otherPersonalInfo;
private int versionNumber;
}
public User(String userId, String name, String surname, String otherPersonalInfo, int version) {
super();
this.name = name;
this.surname = surname;
this.otherPersonalInfo = otherPersonalInfo;
this.version = version;
}
}
Example list:
List<User> users = Arrays.asList(
new User("JOHNSMITH", "John", "Smith", "Some info", 1),
new User("JOHNSMITH", "John", "Smith", "Updated info", 2),
new User("JOHNSMITH", "John", "Smith", "Latest info", 3),
new User("BOBDOE", "Bob", "Doe", "Personal info", 1),
new User("BOBDOE", "Bob", "Doe", "Latest info", 2)
);
I need a way to filter this list such that I get only the latest version for each user, i.e:
{"JOHNSMITH", "John", "Smith", "Latest info", 3},
{"BOBDOE", "Bob", "Doe", "Latest info", 2}
What's the best way to achieve this by using Java8 Stream API?
With a little assistance from this answer:
Collection<User> latestVersions = users.stream()
.collect(Collectors.groupingBy(User::getUserId,
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(User::getVersionNumber)), Optional::get)))
.values();
I am assuming the usual getters. Result:
[John Smith Latest info 3, Bob Doe Latest info 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With