Java Stream:获取最新版本的用户记录

Nic*_*lis 4 java java-8 java-stream

我有一个User对象列表,定义如下:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

示例列表:

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)
);
Run Code Online (Sandbox Code Playgroud)

我需要一种方法来过滤此列表,以便我只获得每个用户的最新版本,即:

{"JOHNSMITH", "John", "Smith", "Latest info", 3},
{"BOBDOE", "Bob", "Doe", "Latest info", 2}
Run Code Online (Sandbox Code Playgroud)

使用Java8 Stream API实现这一目标的最佳方法是什么?

Ole*_*.V. 6

这个答案的帮助下:

    Collection<User> latestVersions = users.stream()
            .collect(Collectors.groupingBy(User::getUserId,
                    Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(User::getVersionNumber)), Optional::get)))
                    .values();
Run Code Online (Sandbox Code Playgroud)

我假设通常的吸气剂.结果:

[John Smith Latest info 3, Bob Doe Latest info 2]
Run Code Online (Sandbox Code Playgroud)

  • @Nick Melis:嗯,异常消息已经说明了.不允许使用`null`键,所以`fullName`,resp.`userId`属性不能为'null`. (2认同)