allencoded
allencoded

Reputation: 7275

JAVA Linked List How to loop through with a for loop?

Hello I am trying to create a for loop that loops through the linked list. For each piece of data it will list it out individually. I am trying to learn linked list here, so no Array suggestions please. Anyone know how to do this?

Example Output:

  1. Flight 187
  2. Flight 501

CODE I HAVE SO FAR BELOW:

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

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

                for (???)


}

Upvotes: 3

Views: 43703

Answers (7)

ozhanli
ozhanli

Reputation: 1496

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));

Upvotes: 0

Thomas Jungblut
Thomas Jungblut

Reputation: 20969

Just use the enhanced for-loop, the same way you'd do it with an array:

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

Upvotes: 16

Srso
Srso

Reputation: 1

while(!flights.isEmptry) {
  System.out.println(flights.removeFirst());
}

Upvotes: -3

eerpini
eerpini

Reputation: 85

If you have distinct values in the linked list , this would 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 distinct values in the linked list, this would 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.

Upvotes: 0

isakkarlsson
isakkarlsson

Reputation: 1109

for(String y : Flights) {
//...
}

The same way as arrays, since it inherits from Iterable<T>

As pointed out by @Cold Hawaiian this only works for Java >= 5.0

If pre 5.0 use:

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

Upvotes: 2

roberttdev
roberttdev

Reputation: 46523

If I understand you correctly, you have to get a reference to the List's iterator and use that to cycle through the data:

ListIterator iterator = Flights.iterator(); 
while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
}

Upvotes: 8

patapizza
patapizza

Reputation: 2398

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

Upvotes: 1

Related Questions