gpt4 book ai didi

Java 流 : get latest version of user records

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:47 24 4
gpt4 key购买 nike

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

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;
}
}

示例列表:

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)
);

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

{"JOHNSMITH", "John", "Smith", "Latest info", 3},
{"BOBDOE", "Bob", "Doe", "Latest info", 2}

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

最佳答案

this answer 的帮助下:

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

我假设是通常的 setter/getter 。结果:

[John Smith Latest info 3, Bob Doe Latest info 2]

关于Java 流 : get latest version of user records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com