JAVA linked list How do I loop with a for loop?

Hello, I am trying to create a for loop that goes through a linked list. For each piece of data, it will be listed separately. I am trying to examine a linked list here, so no Array clauses are needed. Does anyone know how to do this?

Result:

  • Flight 187
  • Flight 501

CODE WHICH I MUST BELOW:

public static LinkedList<String> Flights = new LinkedList<String>();

public flightinfo(){
String[] flightNum = {"187", "501"};
        for (String x : flightNum)
        Flights.add(x);

                for (???)


}
+3
source share
7 answers

Just use the extended for-loop, just like with an array:

for(String flight : flights) {
   // do what you like with it
}
+15
source

If you understand correctly, you need to get a link to the list iterator and use it to cycle through the data:

ListIterator iterator = Flights.iterator(); 
while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
}
+6
source
for(String y : Flights) {
//...
}

, , Iterable<T>

@Cold Hawaiian, Java >= 5.0

pre 5.0 :

ListIterator<String> iter = Flights.iterator();
while(iter.hasNext()) {
  String next = iter.next();
  // use next
}
+1

You should use ListIterator (see Java API for more information).

+1
source

If you have certain values ​​in a linked list, this will work:

for(Iterator<String> i = Flights.listIterator(); i.hasNext();){
    String temp = i.next();
    System.out.println(Flights.indexOf(temp)+1+". Flight "+temp );
}

If you do not have specific values ​​in the linked list, this will work:

int i=0;
for(Iterator<String> iter = Flights.listIterator(); iter.hasNext();i++){
    String temp = iter.next();
    System.out.println(i+1+". Flight "+temp );
}

Hope this helps.

0
source

With Java8 Collection classes that implement Iterable have a forEach () method . With forEach () and lambda expressions, you can easily iterate over LinkedList

flights.forEach(flight -> System.out.println(flight));
0
source
while(!flights.isEmptry) {
  System.out.println(flights.removeFirst());
}
-2
source

All Articles