如果它們屬于同一組,我有共享相同組號的物體串列
| 開始 | 停止 | 組號 |
|---|---|---|
| 2018-11-13 | 2019-01-13 | 1 |
| 2019-01-14 | 2019-03-06 | 1 |
| 2019-03-07 | 2019-11-18 | 1 |
| 2020-08-23 | 2020-08-23 | 2 |
| 2021-11-19 | 2022-12-23 | 2 |
這些物體保存在 ArrayList 中
List<Entities> baseList = new ArrayList<>();
public static class Entities {
private final Date start_dt;
private final Date stop_dt;
private int groupNum;
我想根據 GroupNum 聚合物件,并從 (this).group 的第一個元素中獲取第一個開始日期,并從同一組中獲取最后一個停止日期。
最終結果應如下所示:
| 開始 | 停止 | 組號 |
|---|---|---|
| 2018-11-13 | 2019-11-18 | 1 |
| 2020-08-23 | 2022-12-23 | 2 |
我想分享我的解決方案,但是我想不出任何想法。
提前致謝。
uj5u.com熱心網友回復:
嘗試這個。
public static void main(String[] args) throws ParseException {
List<Entities> baseList = List.of(
new Entities("2018-11-13", "2019-01-13", 1),
new Entities("2019-01-14", "2019-03-06", 1),
new Entities("2019-03-07", "2019-11-18", 1),
new Entities("2020-08-23", "2020-08-23", 2),
new Entities("2021-11-19", "2022-12-23", 2));
List<Entities> result = baseList.stream()
.collect(Collectors.groupingBy(Entities::getGroupNum))
.entrySet().stream()
.map(e -> new Entities(
e.getValue().get(0).getStart_dt(),
e.getValue().get(e.getValue().size() - 1).getStop_dt(),
e.getKey()))
.toList();
result.forEach(System.out::println);
}
輸出:
Entities [start_dt=2018-11-13, stop_dt=2019-11-18, groupNum=1]
Entities [start_dt=2020-08-23, stop_dt=2022-12-23, groupNum=2]
uj5u.com熱心網友回復:
我假設您要匯總Entities如下:
groupNum將是分組標準- 應該使用最早
start_dt和最晚。stop_dt
正如我在評論中已經建議的那樣,請嘗試使用Map<Integer, Entities>密鑰是組號的地方:
Map<Integer, Entities> aggregates = new HashMap<>();
for( Entities entry : baseList ) {
//get the aggregate or create it if none exists for this group
Entities aggregate = aggregates.computeIfAbsent(entry.getGroupNum(),
k -> new Entities(entry.getStart_Dt(), entry.getStop_Dt(), entry.getGroupNum());
//compare and update the dates as needed
if( aggregate.getStart_Dt().compareTo(entry.getStart_Dt()) > 0) {
aggregate.setStart_Dt(entry.getStart_Dt());
}
if( aggregate.getStop_Dt().compareTo(entry.getStop_Dt()) < 0) {
aggregate.setStart_Dt(entry.getStop_Dt());
}
}
幾點注意事項:
這種方法不需要對串列進行排序,也不維護任何順序。如果應維護按組號排序,請使用 a
TreeMap按組號排序或 aLinkedHashMap保持串列的順序(盡可能多地 - 畢竟您正在合并串列元素)如果您使用
java.time,LocalDate而不是java.util.Date您可以使用更易于閱讀的方法isBefore()和isAfter().如果您不想檢查新創建的聚合上的日期,請使用以下代碼段作為回圈主體:
Entities aggregate = aggregates.get(entry.getGroupNum()); if( aggregate == null ) { aggregates.put( entry.getGroupNum(), new Entities(entry.getStart_Dt(), entry.getStop_Dt(), entry.getGroupNum()); } else { if( aggregate.getStart_Dt().compareTo(entry.getStart_Dt()) > 0) { aggregate.setStart_Dt(entry.getStart_Dt()); } if( aggregate.getStop_Dt().compareTo(entry.getStop_Dt()) < 0) { aggregate.setStart_Dt(entry.getStop_Dt()); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529601.html
標籤:爪哇列表
