java数组中根据索引找到对象_Java 8比较同一列表中的对象(数组索引超出...

您的描述与您的代码并不完全同步,因此我将提供一些解决方案,您可以选择其中的一种.

首先,对于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())));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值