Map<groupname,Optional<Person>> test= Personlist.streams.collect(Collectors.groupingBy(x -> x.getgroup(),
Collectors.maxBy(Comparator.comparing(x -> x.getCreateDate()))));
使用上述条件后,我能够迭代并找到最大记录,此后我需要根据上面获取的最大日期迭代并设置每个组的值
记录示例
group 1, 1/1/2020
group 1, 1/2/2020
group 1, 1/3/2020
group 2, 1/1/2020
group 2, 2/1/2020
group 2, 3/1/2020
异常(exception)的输出:(我有恒定的组) 1. 如果组 1 存在,则设置组 1 最大创建日期 = 1/3/2020,否则为 null 2. 如果组 2 存在,则设置组 2 最大创建日期 = 3/1/2020,否则为 null 3. 如果组 3 存在,则设置组 3 最大创建日期 = null(自 不存在)'
if ( group 1 exist)
{<br/>
setgroup1createdate(maxcreatedate) } else setgroup1createdate(null)
}
...有多少组出席
最佳答案
如果您想根据 personlist
中搜索最大日期来设置每个组中的最大日期,您可以首先使用 reducing
来完成此操作方法来创建 Map<String, Optional<Date>>
例如,您在其中存储每个组的最大日期:
Map<String, Optional<Date>> collect =
personList.stream().collect(groupingBy(x -> x.getGroup(),
mapping(Person::getCreationDate, maxBy(Comparator.comparing(Date::getTime)))));
System.out.println(collect);
然后迭代您的组并设置 map 上的最大日期:
groupList.stream().forEach(g ->
g.setCreationDate(collect.getOrDefault(g.getGroup(), Optional.empty()).orElse(null)));
System.out.println(personList);
关于java - 按 key 分组并从给定列表中选择 key 的最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61996552/