我有2个ArrayList:

List<ExcludedCalls> excludedCalls = ExcludedCallJpaDao.me().getExcludedCalls();
List<Calls> callsForSend = CallJpaDao.me().getCallsForSend();

public class ExcludedCalls  {
    private long id;
    private String callingNum;
...
}




public class Calls {
    private long id;
    private Date date;
    private Integer secdur;
    private String condcode;
    private String dialednum;
    private String callingnum;
    private Operators operators;
    private Integer status;
    private PollMessage pollMessage;
...
}


我需要从callingnum包含在excludedCalls中的callsForSend中删除所有项目

我尝试了这个:

public List<Calls> getCallsForSend() {
        List<ExcludedCalls> excludedCalls = ExcludedCallJpaDao.me().getExcludedCalls();
        List<Calls> callsForSend = CallJpaDao.me().getCallsForSend();
        List<Calls> ex = new ArrayList<>();

        for (Calls call : callsForSend) {
            if (excludedCalls.contains(call.getCallingnum())) {
                ex.add(call);
            }
        }
        callsForSend.removeAll(ex);
        return callsForSend;
    }


但是我知道这是错误的。列表具有不同的对象。我可以从Set形成excludedCalls,但是我不需要很多foreach。

最佳答案

我建议您将Iterator<T>与嵌套循环一起使用。比较各个对象中的callingNum,如果相等则将其删除。

Iterator<ExcludedCalls> excludedCallsIterator = excludedCalls.iterator();
Iterator<Calls> callsIterator = callsForSend.iterator();

while (callsIterator.hasNext()) {
  Calls calls = callsIterator.next();
  while (excludedCallsIterator.hasNext()) {
    ExcludedCalls excludedCalls1 = excludedCallsIterator.next();
    if (calls.getCallingnum().equals(excludedCalls1.getCallingNum())) {
      callsIterator.remove();  // remove the object from callsForSend if it matches the current excludedCalls's callingNum.
      break;
    }
  }
}

10-04 22:16
查看更多