英文:
java.util.NoSuchElementException occuring while performing operation on arraylist
问题
我想根据第二个列表中的某些字符串匹配筛选第一个列表。
private void getFilteredList(List<String> fileLst, List<OrderDetailsDTO> msisdnList) {
Iterator<String> it = fileLst.iterator();
while (it.hasNext()) {
for (OrderDetailsDTO item : msisdnList) {
if (it.next() != null && !it.next().contains(item.getMsisdn())) {
it.remove();
}
}
}
}
英文:
I want to filter the first list based on some string match from second list.
private void getFilteredList(List<String> fileLst, List<OrderDetailsDTO> msisdnList) {
Iterator<String> it = fileLst.iterator();
while(it.hasNext()){
for(OrderDetailsDTO item: msisdnList){
if(it.next() != null && ! it.next().contains(item.getMsisdn())){
it.remove();
}
}
}
}
答案1
得分: 0
你正在执行两次 it.next()。一旦执行了 it.hasNext(),你可以直接执行 it.next().contains(item.getMsisdn()),而不需要检查 it.next() != null。
it.next()
返回:
迭代中的下一个元素
抛出:
NoSuchElementException - 如果迭代没有更多元素
因此,在调用 it.next() 之前,应始终调用 it.hasNext()。
请查看
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--
英文:
you are doing it.next() twice. Once you have performed it.hasNext() you can directly perform it.next().contains(item.getMsisdn()) instead of checking it.next() != null.
it.next()
Returns:
the next element in the iteration
Throws:
NoSuchElementException - if the iteration has no more elements
So you should always call it.hasNext() before calling it.next();
Please check
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--
专注分享java语言的经验与见解,让所有开发者获益!
评论