Saturday, April 20, 2019

Java: four ways of looping over a List


List<String> stringList = new LinkedList<String>();
stringList.add("item1");
stringList.add("item2");
stringList.add("item3");

System.out.println("loop 1:");
for (int i = 0; i < stringList.size(); i++) {
    String oneItem = stringList.get(i);
    System.out.println(oneItem);
}

System.out.println("loop 2:");
Iterator<String> iterator = stringList.iterator();
while (iterator.hasNext()) {
    String oneItem = iterator.next();
    System.out.println(oneItem);
}

System.out.println("loop 3:");
for (String oneItem : stringList) {
    System.out.println(oneItem);
}

// Supported by Java 8 and plus
System.out.println("loop 4:");
stringList.forEach(new Consumer<String>() {
    @Override
    public void accept(String s) {
        String oneItem = s;
        System.out.println(oneItem);
    }
});


With the use of Lambda Expressions and Method References (explained in this post), the last loop can be replaced with:

stringList.forEach(System.out::println);


The output of the above four loops in the example is:
loop 1:
item1
item2
item3
loop 2:
item1
item2
item3
loop 3:
item1
item2
item3
loop 4:
item1
item2
item3

No comments:

 
Get This <