java - iterating a linked list












18















if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?










share|improve this question


















  • 3





    Yes it is..

    – Jigar Joshi
    Jan 22 '11 at 11:53
















18















if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?










share|improve this question


















  • 3





    Yes it is..

    – Jigar Joshi
    Jan 22 '11 at 11:53














18












18








18


1






if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?










share|improve this question














if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?







java linked-list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 22 '11 at 11:44









tomermestomermes

9,751143455




9,751143455








  • 3





    Yes it is..

    – Jigar Joshi
    Jan 22 '11 at 11:53














  • 3





    Yes it is..

    – Jigar Joshi
    Jan 22 '11 at 11:53








3




3





Yes it is..

– Jigar Joshi
Jan 22 '11 at 11:53





Yes it is..

– Jigar Joshi
Jan 22 '11 at 11:53












5 Answers
5






active

oldest

votes


















11














Linked list is guaranteed to act in sequential order.



From the documentation




An ordered collection (also known as a
sequence). The user of this interface
has precise control over where in the
list each element is inserted. The
user can access elements by their
integer index (position in the list),
and search for elements in the list.




iterator()
Returns an iterator over the elements in this list in proper sequence.






share|improve this answer

































    37














    I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):





    1. For Loop


    2. Enhanced For Loop


    3. While Loop

    4. Iterator

    5. Collections’s stream() util (Java8)


    For loop



    LinkedList<String> linkedList = new LinkedList<>();
    System.out.println("==> For Loop Example.");
    for (int i = 0; i < linkedList.size(); i++) {
    System.out.println(linkedList.get(i));
    }


    Enhanced for loop



    for (String temp : linkedList) {
    System.out.println(temp);
    }


    While loop



    int i = 0;
    while (i < linkedList.size()) {
    System.out.println(linkedList.get(i));
    i++;
    }


    Iterator



    Iterator<String> iterator = linkedList.iterator();
    while (iterator.hasNext()) {
    System.out.println(iterator.next());
    }


    collection stream() util (Java 8)



    linkedList.forEach((temp) -> {
    System.out.println(temp);
    });


    One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.






    share|improve this answer


























    • Great. I didn't know about LinkedList.size() . +1.

      – roottraveller
      Jul 20 '17 at 10:09













    • For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

      – Tarun
      Dec 31 '18 at 8:25













    • Linear time and O(n) are the same, aren't they?

      – pooria
      Mar 5 at 6:26



















    7














    As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.



    eg:



    import java.util.LinkedList;

    public class ForEachDemonstrater {
    public static void main(String args) {
    LinkedList<Character> pl = new LinkedList<Character>();
    pl.add('j');
    pl.add('a');
    pl.add('v');
    pl.add('a');
    for (char s : pl)
    System.out.print(s+"->");
    }
    }





    share|improve this answer































      0














      Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)






      share|improve this answer































        0














        Linked list does guarantee sequential order.



        Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.



        Use ListIterator



            ListIterator<Object> iterator = wordTokensListJava.listIterator();
        while( iterator.hasNext()) {
        System.out.println(iterator.next());
        }





        share|improve this answer
























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4767615%2fjava-iterating-a-linked-list%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          11














          Linked list is guaranteed to act in sequential order.



          From the documentation




          An ordered collection (also known as a
          sequence). The user of this interface
          has precise control over where in the
          list each element is inserted. The
          user can access elements by their
          integer index (position in the list),
          and search for elements in the list.




          iterator()
          Returns an iterator over the elements in this list in proper sequence.






          share|improve this answer






























            11














            Linked list is guaranteed to act in sequential order.



            From the documentation




            An ordered collection (also known as a
            sequence). The user of this interface
            has precise control over where in the
            list each element is inserted. The
            user can access elements by their
            integer index (position in the list),
            and search for elements in the list.




            iterator()
            Returns an iterator over the elements in this list in proper sequence.






            share|improve this answer




























              11












              11








              11







              Linked list is guaranteed to act in sequential order.



              From the documentation




              An ordered collection (also known as a
              sequence). The user of this interface
              has precise control over where in the
              list each element is inserted. The
              user can access elements by their
              integer index (position in the list),
              and search for elements in the list.




              iterator()
              Returns an iterator over the elements in this list in proper sequence.






              share|improve this answer















              Linked list is guaranteed to act in sequential order.



              From the documentation




              An ordered collection (also known as a
              sequence). The user of this interface
              has precise control over where in the
              list each element is inserted. The
              user can access elements by their
              integer index (position in the list),
              and search for elements in the list.




              iterator()
              Returns an iterator over the elements in this list in proper sequence.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 22 '11 at 11:58









              Jigar Joshi

              202k37345390




              202k37345390










              answered Jan 22 '11 at 11:49









              Dave GDave G

              8,1532839




              8,1532839

























                  37














                  I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):





                  1. For Loop


                  2. Enhanced For Loop


                  3. While Loop

                  4. Iterator

                  5. Collections’s stream() util (Java8)


                  For loop



                  LinkedList<String> linkedList = new LinkedList<>();
                  System.out.println("==> For Loop Example.");
                  for (int i = 0; i < linkedList.size(); i++) {
                  System.out.println(linkedList.get(i));
                  }


                  Enhanced for loop



                  for (String temp : linkedList) {
                  System.out.println(temp);
                  }


                  While loop



                  int i = 0;
                  while (i < linkedList.size()) {
                  System.out.println(linkedList.get(i));
                  i++;
                  }


                  Iterator



                  Iterator<String> iterator = linkedList.iterator();
                  while (iterator.hasNext()) {
                  System.out.println(iterator.next());
                  }


                  collection stream() util (Java 8)



                  linkedList.forEach((temp) -> {
                  System.out.println(temp);
                  });


                  One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.






                  share|improve this answer


























                  • Great. I didn't know about LinkedList.size() . +1.

                    – roottraveller
                    Jul 20 '17 at 10:09













                  • For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                    – Tarun
                    Dec 31 '18 at 8:25













                  • Linear time and O(n) are the same, aren't they?

                    – pooria
                    Mar 5 at 6:26
















                  37














                  I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):





                  1. For Loop


                  2. Enhanced For Loop


                  3. While Loop

                  4. Iterator

                  5. Collections’s stream() util (Java8)


                  For loop



                  LinkedList<String> linkedList = new LinkedList<>();
                  System.out.println("==> For Loop Example.");
                  for (int i = 0; i < linkedList.size(); i++) {
                  System.out.println(linkedList.get(i));
                  }


                  Enhanced for loop



                  for (String temp : linkedList) {
                  System.out.println(temp);
                  }


                  While loop



                  int i = 0;
                  while (i < linkedList.size()) {
                  System.out.println(linkedList.get(i));
                  i++;
                  }


                  Iterator



                  Iterator<String> iterator = linkedList.iterator();
                  while (iterator.hasNext()) {
                  System.out.println(iterator.next());
                  }


                  collection stream() util (Java 8)



                  linkedList.forEach((temp) -> {
                  System.out.println(temp);
                  });


                  One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.






                  share|improve this answer


























                  • Great. I didn't know about LinkedList.size() . +1.

                    – roottraveller
                    Jul 20 '17 at 10:09













                  • For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                    – Tarun
                    Dec 31 '18 at 8:25













                  • Linear time and O(n) are the same, aren't they?

                    – pooria
                    Mar 5 at 6:26














                  37












                  37








                  37







                  I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):





                  1. For Loop


                  2. Enhanced For Loop


                  3. While Loop

                  4. Iterator

                  5. Collections’s stream() util (Java8)


                  For loop



                  LinkedList<String> linkedList = new LinkedList<>();
                  System.out.println("==> For Loop Example.");
                  for (int i = 0; i < linkedList.size(); i++) {
                  System.out.println(linkedList.get(i));
                  }


                  Enhanced for loop



                  for (String temp : linkedList) {
                  System.out.println(temp);
                  }


                  While loop



                  int i = 0;
                  while (i < linkedList.size()) {
                  System.out.println(linkedList.get(i));
                  i++;
                  }


                  Iterator



                  Iterator<String> iterator = linkedList.iterator();
                  while (iterator.hasNext()) {
                  System.out.println(iterator.next());
                  }


                  collection stream() util (Java 8)



                  linkedList.forEach((temp) -> {
                  System.out.println(temp);
                  });


                  One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.






                  share|improve this answer















                  I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):





                  1. For Loop


                  2. Enhanced For Loop


                  3. While Loop

                  4. Iterator

                  5. Collections’s stream() util (Java8)


                  For loop



                  LinkedList<String> linkedList = new LinkedList<>();
                  System.out.println("==> For Loop Example.");
                  for (int i = 0; i < linkedList.size(); i++) {
                  System.out.println(linkedList.get(i));
                  }


                  Enhanced for loop



                  for (String temp : linkedList) {
                  System.out.println(temp);
                  }


                  While loop



                  int i = 0;
                  while (i < linkedList.size()) {
                  System.out.println(linkedList.get(i));
                  i++;
                  }


                  Iterator



                  Iterator<String> iterator = linkedList.iterator();
                  while (iterator.hasNext()) {
                  System.out.println(iterator.next());
                  }


                  collection stream() util (Java 8)



                  linkedList.forEach((temp) -> {
                  System.out.println(temp);
                  });


                  One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 26 '18 at 13:03









                  Alex Sicoe

                  6018




                  6018










                  answered Jun 25 '16 at 18:02









                  Gherbi HichamGherbi Hicham

                  1,49831428




                  1,49831428













                  • Great. I didn't know about LinkedList.size() . +1.

                    – roottraveller
                    Jul 20 '17 at 10:09













                  • For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                    – Tarun
                    Dec 31 '18 at 8:25













                  • Linear time and O(n) are the same, aren't they?

                    – pooria
                    Mar 5 at 6:26



















                  • Great. I didn't know about LinkedList.size() . +1.

                    – roottraveller
                    Jul 20 '17 at 10:09













                  • For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                    – Tarun
                    Dec 31 '18 at 8:25













                  • Linear time and O(n) are the same, aren't they?

                    – pooria
                    Mar 5 at 6:26

















                  Great. I didn't know about LinkedList.size() . +1.

                  – roottraveller
                  Jul 20 '17 at 10:09







                  Great. I didn't know about LinkedList.size() . +1.

                  – roottraveller
                  Jul 20 '17 at 10:09















                  For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                  – Tarun
                  Dec 31 '18 at 8:25







                  For iteration just using linkedList.forEach(e -> System.out.println(e)); would also work.

                  – Tarun
                  Dec 31 '18 at 8:25















                  Linear time and O(n) are the same, aren't they?

                  – pooria
                  Mar 5 at 6:26





                  Linear time and O(n) are the same, aren't they?

                  – pooria
                  Mar 5 at 6:26











                  7














                  As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.



                  eg:



                  import java.util.LinkedList;

                  public class ForEachDemonstrater {
                  public static void main(String args) {
                  LinkedList<Character> pl = new LinkedList<Character>();
                  pl.add('j');
                  pl.add('a');
                  pl.add('v');
                  pl.add('a');
                  for (char s : pl)
                  System.out.print(s+"->");
                  }
                  }





                  share|improve this answer




























                    7














                    As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.



                    eg:



                    import java.util.LinkedList;

                    public class ForEachDemonstrater {
                    public static void main(String args) {
                    LinkedList<Character> pl = new LinkedList<Character>();
                    pl.add('j');
                    pl.add('a');
                    pl.add('v');
                    pl.add('a');
                    for (char s : pl)
                    System.out.print(s+"->");
                    }
                    }





                    share|improve this answer


























                      7












                      7








                      7







                      As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.



                      eg:



                      import java.util.LinkedList;

                      public class ForEachDemonstrater {
                      public static void main(String args) {
                      LinkedList<Character> pl = new LinkedList<Character>();
                      pl.add('j');
                      pl.add('a');
                      pl.add('v');
                      pl.add('a');
                      for (char s : pl)
                      System.out.print(s+"->");
                      }
                      }





                      share|improve this answer













                      As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.



                      eg:



                      import java.util.LinkedList;

                      public class ForEachDemonstrater {
                      public static void main(String args) {
                      LinkedList<Character> pl = new LinkedList<Character>();
                      pl.add('j');
                      pl.add('a');
                      pl.add('v');
                      pl.add('a');
                      for (char s : pl)
                      System.out.print(s+"->");
                      }
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 13 '11 at 11:15









                      krantboykrantboy

                      9113




                      9113























                          0














                          Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)






                          share|improve this answer




























                            0














                            Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)






                            share|improve this answer


























                              0












                              0








                              0







                              Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)






                              share|improve this answer













                              Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 22 '11 at 14:01









                              Marcin MichalskiMarcin Michalski

                              1,1401117




                              1,1401117























                                  0














                                  Linked list does guarantee sequential order.



                                  Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.



                                  Use ListIterator



                                      ListIterator<Object> iterator = wordTokensListJava.listIterator();
                                  while( iterator.hasNext()) {
                                  System.out.println(iterator.next());
                                  }





                                  share|improve this answer




























                                    0














                                    Linked list does guarantee sequential order.



                                    Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.



                                    Use ListIterator



                                        ListIterator<Object> iterator = wordTokensListJava.listIterator();
                                    while( iterator.hasNext()) {
                                    System.out.println(iterator.next());
                                    }





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      Linked list does guarantee sequential order.



                                      Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.



                                      Use ListIterator



                                          ListIterator<Object> iterator = wordTokensListJava.listIterator();
                                      while( iterator.hasNext()) {
                                      System.out.println(iterator.next());
                                      }





                                      share|improve this answer













                                      Linked list does guarantee sequential order.



                                      Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.



                                      Use ListIterator



                                          ListIterator<Object> iterator = wordTokensListJava.listIterator();
                                      while( iterator.hasNext()) {
                                      System.out.println(iterator.next());
                                      }






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 5 at 11:21









                                      Caleb HillaryCaleb Hillary

                                      11




                                      11






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4767615%2fjava-iterating-a-linked-list%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Wiesbaden

                                          Marschland

                                          Dieringhausen