根据多个字段过滤对象的 ArrayList
Filter an ArrayList of objects based on more than one field
所以这是我的 class:
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
}
我有一个List<A> list1
所以在这个列表中,如果任何两个对象具有相同的 startDate
和相同的 source
,那么我需要 select 具有更高 endDate
的对象。我怎样才能实现它?
我当前的实现:(它只检查 startDate
而不是 source
然后 select 更高的 endDate
值)
Collection<A> result =
list1.stream()
.collect(Collectors.toMap(A::getStartDate,
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();
我如何扩展此代码以检查源代码或任何其他执行相同操作的实现也很好...
您可以在 A
中添加一个方法,它根据 startDate
和 source
生成一个 String
密钥。然后你可以在 toMap
:
中使用它
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
public String getKey() {
return this.startDate.toString() + source;
}
}
list1.stream()
.collect(Collectors.toMap(A::getKey,
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();
@Getter
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
}
list1.stream()
.collect(Collectors.toMap(a -> a.getStartDate()+a.getSource(),
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();
所以这是我的 class:
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
}
我有一个List<A> list1
所以在这个列表中,如果任何两个对象具有相同的 startDate
和相同的 source
,那么我需要 select 具有更高 endDate
的对象。我怎样才能实现它?
我当前的实现:(它只检查 startDate
而不是 source
然后 select 更高的 endDate
值)
Collection<A> result =
list1.stream()
.collect(Collectors.toMap(A::getStartDate,
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();
我如何扩展此代码以检查源代码或任何其他执行相同操作的实现也很好...
您可以在 A
中添加一个方法,它根据 startDate
和 source
生成一个 String
密钥。然后你可以在 toMap
:
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
public String getKey() {
return this.startDate.toString() + source;
}
}
list1.stream()
.collect(Collectors.toMap(A::getKey,
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();
@Getter
class A {
private int id;
private TimeStamp startDate;
private TimeStamp endDate;
private String source;
}
list1.stream()
.collect(Collectors.toMap(a -> a.getStartDate()+a.getSource(),
Function.identity(),
(a, b) -> a.getEndDate().after(b.getEndDate()) ? a : b))
.values();