Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through lists, better method

As I’m coding and discovering new ways of doing things in Java, I’m always somewhat perplexed in the better method of looping through lists to output data.

In the following example, I’m looping through lists and using a counter, so many times I’ve had to include an index counter in the output.

I'm partial to Method 1 but I found any of these method a bit dated. I’ve seen many examples of looping through lists and Method 2 is mostly used.

So my question is what is the better method, if all of these methods are just as equal, then what is the most standard?

private ArrayList<String> list = new ArrayList<String>();

public Test() {
    list.add("One");        
    list.add("Two");        
    list.add("Three");      
    list.add("Four");       
    list.add("Five");

    method1();
    method2();
    method3();
}

public void method1() {
    System.out.println("Method 1");
    int i = 1;
    for (String value:list) {
        System.out.println((i++) + " = " + value);
    }
}

public void method2() {
    System.out.println("Method 2");
    for (int i = 0; i < list.size(); i++) {
        System.out.println((i+1) + " = " + list.get(i));
    }
}

public void method3() {
    System.out.println("Method 3");
    Iterator<String> it = list.iterator();
    int i = 1;
    while (it.hasNext()) {
        System.out.println((i++) + " = " + it.next());
    }
}
like image 966
GeekyDaddy Avatar asked Mar 24 '15 12:03

GeekyDaddy


People also ask

Which type of loop is most effective to iterate over a list?

While loop It works on any Collection ( List or Set ).

Is it faster to iterate over a list or a set?

Iterating over a List is much much faster than iterating over a set. The currently accepted answer is using a very small set and list and hence, the difference is negligible there.

Can you loop through a list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

How do you iterate over two or more lists at the same time?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.


2 Answers

method1() is similar to method3() as the for-each loop uses the List's iterator behind the scenes. The difference with method3() is that you actually have access to this iterator, so you can call remove on it if you wish to remove elements from the list.

method2()on the other hand can lead to "bad" performances depending on the underlying implementation. If your list is a LinkedList, get has O(n) complexity time so the for-loop will have O(n^2) complexity. With the iterator, you'll always get the next element in constant time.

I would personally use 1, it's also less code to write and this is one of the main benefit of the for-each loop if your intent is to perform a read-only operation on your data structure.

If you are using Java 8 and you don't need to print the index, you could also do:

list.forEach(System.out::println);
like image 59
Alexis C. Avatar answered Oct 11 '22 22:10

Alexis C.


The first is better and least error prone.

public void method1() {
    System.out.println("Method 1");
    int i = 1;
    for (String value:list) {
        System.out.println((i++) + " = " + value);
    }
}

The second options is tightly coupled with the Collection you are using. It means, if someone changes the data structures then he/she has to change the code for the for loop as well.

The third option, Iterators can get ugly when you have to use nested loops and have to deal with multiple iterators.

Have a look at following link to see the error prone usage of iterators. https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html

like image 29
suranjan Avatar answered Oct 11 '22 22:10

suranjan