您的描述与您的代码并不完全同步,因此我将提供一些解决方案,您可以选择其中的一种.
首先,对于IndexOutOfBoundsException,您可以通过将循环条件从i< = tl.size()更改为itradeMap.values()
.stream()
.filter(list -> list.size() > 1)
.forEach(T::accept);
其中accept定义为:
private static void accept(List list) {
String et = list.get(0).getTradeType();
list.subList(1, list.size()).removeIf(e -> e.getTradeType().equals(et));
}
和T应该替换为包含accept方法的类.
上面的代码段仅按交易类型删除第一个元素之后的对象,该对象等于第一个元素,这就是您的示例代码段所尝试的操作.但是,如果您想区分所有对象,则一种选择是重写Trade类中的equals和hashcode,如下所示:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Trade trade = (Trade) o;
return Objects.equals(tradeType, trade.tradeType);
}
@Override
public int hashCode() {
return Objects.hash(tradeType);
}
然后需要将accept方法修改为:
private static void accept(List list) {
List distinct = list.stream()
.distinct()
.collect(Collectors.toList());
list.clear(); // clear list
list.addAll(distinct); // repopulate with distinct objects by tradeType
}
或者,如果您根本不想覆盖equals和hashcode,则可以使用toMap收集器来获取不同的对象:
private static void accept(List list) {
Collection distinct = list.stream()
.collect(Collectors.toMap(Trade::getTradeType,
Function.identity(), (l, r) -> l, LinkedHashMap::new))
.values();
list.clear(); // clear list
list.addAll(distinct); // repopulate with distinct objects by tradeType
}
但是,如果您说:
“If any two of the object’s property name “TradeType” is same then I
have to remove those two from the list.”
您实际上想要通过tradeType删除所有相等的Trade对象,这些对象具有两次或多次出现,然后将accept方法修改如下:
private static void accept(List list) {
list.stream()
.collect(Collectors.groupingBy(Trade::getTradeType))
.values()
.stream()
.filter(l -> l.size() > 1)
.map(l -> l.get(0))
.forEach(t -> list.removeIf(trade -> trade.getTradeType().equals(t.getTradeType())));
}