英文:
Filter only the needed duplicate records from List of Objects java (version less than 8)
问题
我必须从对象列表中筛选出重复项,这相当容易。但是,在筛选重复项时,我有一个内部条件。以下是我的代码。
List<Person> personsList = Arrays.asList(
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:32:46"), status: 'Accepted'),
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:30:49"), status: 'Rejected'),
new Person(ID: 3456, dateOfJoin: new Date("2020-08-29 13:23:34"), status: 'Waiting'));
我必须筛选出 personsList
其中 ID 相等,并且我必须获取最近的 dateOfJoin 的人员。因此,我的最终筛选列表将如下所示。
List<Person> filteredPersonsList = Arrays.asList(
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:30:49"), status: 'Rejected'),
new Person(ID: 3456, dateOfJoin: new Date("2020-08-29 13:23:34"), status: 'Waiting'));
如何筛选这个列表?请问有什么建议吗?
谢谢。
英文:
I have to filter the duplicates from list of objects which is pretty easy. But, here I have an internal condition while filtering the duplicates. Here is my code.
List<Person> personsList = Arrays.asList(
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:32:46"), status: 'Accepted'),
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:30:49"), status: 'Rejected'),
new Person(ID: 3456, dateOfJoin: new Date("2020-08-29 13:23:34"), status: 'Waiting'));
I have to filter the personsList where ID is equal and I have to get the most recent dateOfJoin person. So, my final filtered list would be like the following.
List<Person> filteredPersonsList = Arrays.asList(
new Person(ID: 1234, dateOfJoin: new Date("2020-08-31 17:30:49"), status: 'Rejected'),
new Person(ID: 3456, dateOfJoin: new Date("2020-08-29 13:23:34"), status: 'Waiting'));
How could I filter this? Any suggestions please?
Thanks.
答案1
得分: 2
假设存在相应的获取器,看起来像这样。
Collection<Person> result = personList.stream()
.collect(Collectors.groupingBy(
Person::getId,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getDateOfJoin)),
Optional::get))
.values();
不幸的是,maxBy
返回 Optional
,需要进一步解包。
英文:
Assuming there are corresponding getters look like this.
Collection<Person> result = personList.stream()
.collect(Collectors.groupingBy(
Person::getId,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getDateOfJoin),
Optional::get)))
.values();
Unfortunately, maxBy
returns Optional
and needs further unwrapping
答案2
得分: 2
你可以使用 toMap
和 maxBy
来获取具有相同 id 的最大 dateOfJoin
,并将映射的值放入一个 ArrayList 中。
List<Person> filteredPersonsList = new ArrayList<>(personsList
.stream()
.collect(Collectors.toMap(Person::getID, Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(Person::getDateOfJoin))))
.values());
英文:
You can use toMap
and maxBy
to get max dateOfJoin
with same id and take values of the map in an ArrayList.
List<Person> filteredPersonsList =
new ArrayList<>(personsList
.stream()
.collect(Collectors.toMap(Person::getID, Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(Person::getDateOfJoin))))
.values());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论