[英]how can I get the next object on my linkedlist?
I have a LinkedList
of objects in Java
and I want to iterate through it, and when I find a specific object there - I want to take the next object (the one that is right next to the first one). 我在Java
有一个对象的LinkedList
,我想遍历它,当我在其中找到一个特定的对象时-我要拿下一个对象(紧挨着第一个对象)。
I thought this would solve the case: 我认为这可以解决问题:
listIterator = items.listIterator();
while (listIterator.hasNext() && listIterator.previous().getCode().equals(search.getCurrentCode())) {
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
but I'm getting error: 但我收到错误消息:
java.util.NoSuchElementException: null
I think it's because of using .previous
, but I don't know how to handle that correctly, how could I solve it then? 我认为是因为使用了.previous
,但是我不知道如何正确处理它,那我该如何解决呢? I'm using previous
, but what I want is to use the current element - I thought that's handled by .previous
, but apparently it's not. 我正在使用previous
,但是我想使用的是当前元素-我认为这是由.previous
处理的,但显然不是。
Your current code fails because You are calling previous, before even start iterating on items. 您当前的代码失败,因为您甚至在迭代项目之前就调用了先前的代码。 Iteration is done with listIterator.next();
迭代是通过listIterator.next();
完成的listIterator.next();
call. 呼叫。 You can try the code below. 您可以尝试下面的代码。
while (listIterator.hasNext()){
// iterate always
item = listIterator.next();
// if found and an element still exist
if(item.getCode().equals(search.getCurrentCode() && listIterator.hasNext()){
// get the next element
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
}
Try this: 尝试这个:
listIterator = items.listIterator();
// listIterator.previous() does not exist in first iteration
while (listIterator.hasNext()) {
// you can compare previous value if it exist
if(listIterator.hasPrevious() && listIterator.previous().getCode().equals(search.getCurrentCode())){
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
}
First, I'd suggest using an ArrayList
instead of LinkedList
as the former is almost always the better option to use. 首先,我建议使用ArrayList
而不是LinkedList
因为前者几乎总是更好的选择。 see this post for more information. 有关更多信息, 请参见这篇文章 。
You could definitely do this via a typical for loop or enhanced for loop, but I'd like to illustrate a new method as of JDK9 called dropWhile
which can help you accomplish this requirement of yours: 您绝对可以通过典型的for循环或增强的for循环来执行此操作,但是我想说明一种从JDK9开始的名为dropWhile
的新方法,它可以帮助您实现您的要求:
Assuming, you have your ArrayList
in place. 假设您有适当的ArrayList
。 you could simply do: 您可以简单地做:
myList.stream()
.dropWhile(c -> !c.getCode().equals(search.getCurrentCode()))
.skip(1) // get the object to the right of the matched item
.findFirst() // retrieve this object
.ifPresent(s -> result.setCurrentCode(s.getCode())); // apply the logic based on the found object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.