想要通过按属性对其他对象列表进行分组来创建新列表
Want to create a new list by grouping the other list of objects by attribute
想要通过按属性对其他对象列表进行分组来创建一个列表
代码是这样的:
public class MyDate {
public static void main(String[] args) {
List<Data> list = new ArrayList<>();
list.add(new Data("NEW",todayDate,todayDatePlus1,"N"));
list.add(new Data("AUTORIZED",todayDate,todayDatePlus1,"Y"));
list.add(new Data("AUTORIZED",todayDatePlus1,todayDatePlus3,"Y"));
list.add(new Data("AUTHENTICATE",todayDate,todayDatePlus1,"Y"));
list.add(new Data("AUTHENTICATE",todayDatePlus1,todayDatePlus2,"Y"));
list.add(new Data("COMPLETED",todayDate,todayDatePlus1,"N"));
}
}
@Getter
@Setter
class Data{
String phase;
LocalDate startDate;
LocalDate endDate;
String required;
Data(String phase, LocalDate startDate, LocalDate endDate, String required) {
this.phase = phase;
this.startDate = startDate;
this.endDate = endDate;
this.required = required;
}
}
输出:
In New List
("NEW",todayDate,todayDatePlus1,"N")
**("AUTORIZED",todayDate,todayDatePlus3,"Y")**
**("AUTHENTICATE",todayDate,todayDatePlus2,"Y")**
("COMPLETED",todayDate,todayDatePlus1,"N")
在新列表中,重复的属性phase 合并为1,并且StartDate 和EndDate 也被更新。 (StartDate 最早一个,EndDate 是最后一个)
您可以使用 Collectors.toMap 和 mergefunction
,合并具有相同 phase
的 Data
对象的值
Collection<Data> result = list.stream()
.collect(Collectors.toMap(Data::getPhase, Function.identity(), ((existing, replacement) -> {
// Merge values of replacement with existing
existing.setEndDate(replacement.getEndDate());
return existing;
}))).values();
想要通过按属性对其他对象列表进行分组来创建一个列表 代码是这样的:
public class MyDate {
public static void main(String[] args) {
List<Data> list = new ArrayList<>();
list.add(new Data("NEW",todayDate,todayDatePlus1,"N"));
list.add(new Data("AUTORIZED",todayDate,todayDatePlus1,"Y"));
list.add(new Data("AUTORIZED",todayDatePlus1,todayDatePlus3,"Y"));
list.add(new Data("AUTHENTICATE",todayDate,todayDatePlus1,"Y"));
list.add(new Data("AUTHENTICATE",todayDatePlus1,todayDatePlus2,"Y"));
list.add(new Data("COMPLETED",todayDate,todayDatePlus1,"N"));
}
}
@Getter
@Setter
class Data{
String phase;
LocalDate startDate;
LocalDate endDate;
String required;
Data(String phase, LocalDate startDate, LocalDate endDate, String required) {
this.phase = phase;
this.startDate = startDate;
this.endDate = endDate;
this.required = required;
}
}
输出:
In New List
("NEW",todayDate,todayDatePlus1,"N")
**("AUTORIZED",todayDate,todayDatePlus3,"Y")**
**("AUTHENTICATE",todayDate,todayDatePlus2,"Y")**
("COMPLETED",todayDate,todayDatePlus1,"N")
在新列表中,重复的属性phase 合并为1,并且StartDate 和EndDate 也被更新。 (StartDate 最早一个,EndDate 是最后一个)
您可以使用 Collectors.toMap 和 mergefunction
,合并具有相同 phase
Data
对象的值
Collection<Data> result = list.stream()
.collect(Collectors.toMap(Data::getPhase, Function.identity(), ((existing, replacement) -> {
// Merge values of replacement with existing
existing.setEndDate(replacement.getEndDate());
return existing;
}))).values();