Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream: get latest version of user records

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?

like image 765
Nick Melis Avatar asked Dec 23 '22 20:12

Nick Melis


1 Answers

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]
like image 155
Ole V.V. Avatar answered Dec 26 '22 12:12

Ole V.V.