Java loop comparison: traditional for loop, enhanced for loop and forEach loop

1. Traditional for loop

The traditional for loop is a classic loop structure widely used in Java.

The following are the characteristics of the traditional for loop:

Flexible control: Traditional for loops use syntax in the form of for (initialization expression; termination condition; step expression). You can manually control the index of the loop and perform custom operations as needed.

Index access: The traditional for loop accesses elements in a collection or array through indexes, and can directly read and modify the value of the element.

For example:

import java.util.Arrays;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        for (int i = 0; i < numbers.size(); i++) {
            System.out.println(numbers.get(i));  // 读取元素的属性值或执行操作是允许的
            numbers.set(i, 10);  // 直接修改元素的值是允许的
        }
    }
}

Low-level operations: Compared with the enhanced for loop, the traditional for loop provides lower-level operations, which is more flexible, but also more cumbersome.

Applicable objects: Applicable to any collection class that implements the Iterable or Iterator interface.

Sample code:

public class Demo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}

The traditional for loop code structure is like this:

for (initial declaration of loop variable; determination condition of loop; condition of changing loop variable){

loop body

}

The execution order is: ① Initial declaration of loop variables (declaring loop variables) ② Judgment conditions of the loop (determining whether to continue executing the loop, which is a boolean value) ③ Loop body (the code segment that you want to execute repeatedly) ④ Conditions for changing the loop variables (Used to end the loop) ⑤ Return to step 2 to determine whether to jump out of the loop. If the result is true, continue the above process. If the judgment result is false, jump out of the entire loop code segment and execute the subsequent code.

For example, the test implements assignment to the array through traversal, and the assignment is 100, 200, 300, 400, 500.

import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        int[] arr = new int[5];
        int num = 100;
        for (int i = 0; i < arr.length; i++) {
            arr[i] = num;
            num += 100;
        }
        System.out.println(Arrays.toString(arr));
    }
}

The output of the code is like this: [100, 200, 300, 400, 500]

Obviously, the ordinary for loop assigns the value to the inside of the array through the subscript index.

2. Enhanced for loop

The enhanced for loop, also called foreach loop, is a simplified version of loop syntax. It can be used to iterate over an array or a collection class that implements the Iterable interface.

The following are the characteristics of the enhanced for loop:

Concise syntax: The enhanced for loop uses the syntax in the form of for (element type element variable: collection or array), making the code easier to read and write.

Read-only access: In each iteration, the enhanced for loop provides read-only access to the current element and cannot directly modify the element's value.

For example:

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("World");
        System.out.println(list);
        for (String s : list) {
            s = "New Value";  // 尝试修改元素的值
        }
        System.out.println(list);
    }
}

 

Applicable objects: Applicable to arrays or collection classes that implement the Iterable interface.

Sample code:

import java.util.Arrays;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Orange");
        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

 

The enhanced for loop code structure is as follows:

for (type variable name that receives array elements: array){

The variable name represents each data in the array

}

Enhanced for can traverse each element in the array and receive it using the previous variable name. I emphasize receiving, because the variables defined by the type are only used to receive each element in the array, rather than separating each element.

As listed above, the test uses two traversal methods to assign values ​​to the array respectively. The assigned values ​​are 100, 200, 300, 400, 500.

import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        int[] arr = new int[5];
        int num = 100;
        for (int i : arr) {
            i = num;
            num += 100;
        }
        System.out.println(Arrays.toString(arr));
    }
}

The code output is like this: [0, 0, 0, 0, 0]

In other words, the enhanced for loop does not pass the value into the array at all. This is also the difference between ordinary for and enhanced for. The ordinary for loop can assign values ​​to the array and operate according to the index; foreach can only traverse and obtain, and cannot modify the data in the array.

In addition,: The front is the type of receiving array elements. What is emphasized here is that the type defined here is the type of receiving array elements, and does not have to be the type relationship of the array.

for(long|float|double|.. i:arr){
	i=num;
	num+=100;
}

In fact, the type is not that strict, as long as it can receive the elements of the int-type array arr. Of course, other types that cannot be received, such as byte, short, char... will report an error.

 

3. forEach loop _

forEach is a method introduced in Java 8 that is used to iterate over the elements in a collection and perform some operation on them. It can accept a function as a parameter, which will operate on each element in the collection. This function can be a Lambda expression or a normal function interface.

Lambda expressions were introduced in Java 8 as a concise, functional way to write certain operations. Lambda expressions are mainly used to create interfaces with only one method. This interface can contain a parameter list and an expression or a block statement. This expression or block statement is the Lambda body.

The following are the characteristics of Lambda expression for loop:

Functional style: Lambda expression for loop adopts functional programming style. The operation of the loop body is defined through Lambda expression, making the code more concise and readable.

Automatic iteration: Similar to enhanced for loops, Lambda expression for loops automatically iterate over elements in a collection or array without manual control of indexing.

For example:

import java.util.Arrays;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
        // 使用Java 8的forEach和Lambda表达式
        list.forEach(fruit -> System.out.println(fruit));
    }
}

4. Simple comparison of efficiency

Note: The test may not be rigorous in terms of time, machine, execution sequence, or the efficiency may be reduced after the CPU is run. This is for reference only.

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        long[] numbers = {10000L, 100000L, 1000000L, 10000000L};
        for (int j= 0; j < numbers.length; j++) {
            long times = numbers[j];
            System.out.println("操作次数:" + times);
            List<String> list = new ArrayList<>();
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            List<String> list3 = new ArrayList<>();
            for (int i = 0; i < times; i++) {
                list.add(new String());
            }
            long startTime = System.currentTimeMillis();
            //普通for
            for (int i = 0; i < list.size(); i++) {
                list1.add(list.get(i));
            }
            long endTime = System.currentTimeMillis();
            System.out.println("普通for时间(毫秒):" + (endTime - startTime));
            //增强for
            long startTime1 = System.currentTimeMillis();
            for (String s : list) {
                list2.add(s);
            }
            long endTime1 = System.currentTimeMillis();
            System.out.println("增强for时间(毫秒):" + (endTime1 - startTime1));

            long startTime2 = System.currentTimeMillis();
            //forEach
            list.forEach(s -> list3.add(s));
            long endTime2 = System.currentTimeMillis();
            System.out.println("forEach时间(毫秒):" + (endTime2 - startTime2));
        }
    }
}

Results of the:

Number of operations: 10000

Ordinary for time (milliseconds): 1

Enhanced for time (milliseconds): 1

forEach time (milliseconds):59

Number of operations: 100000

Ordinary for time (milliseconds): 2

Enhanced for time (milliseconds): 2

forEach time (milliseconds): 3

Number of operations: 1000000

Ordinary for time (milliseconds): 37

Enhanced for time (milliseconds): 10

forEach time (milliseconds): 8

Number of operations: 10000000

Ordinary for time (milliseconds): 203

Enhanced for time (milliseconds): 170

forEach time (milliseconds):184

5. Selection of applicable scenarios

Choosing the appropriate recycling method depends on the specific needs and operation. Here are some suggested usage scenarios:

Traditional for loop: suitable for scenarios where you need to manually control indexes, perform custom operations, or modify the values ​​of collection or array elements.

Enhanced for loop: suitable for simple traversal and read-only operations that do not require modifying the elements of the collection or array.

Lambda expression + forEach loop: suitable for functional programming style, simplifying the code and eliminating the need to manually control the index.

According to specific needs, we can flexibly choose different loop methods to achieve a balance between code simplicity, readability and performance.

Guess you like

Origin blog.csdn.net/xijinno1/article/details/133326054