[Learn JAVA from scratch | Article 24] Traversal of single-column collections

Table of contents

Foreword:

How to traverse a single-column collection:

The iterator traverses:

Enhanced for traversal:

The lambda method traverses: 

Summarize:


Foreword:

In this article, we will explain several traversal methods for single-column collections. Traversing collections can be said to be the minimum skill required for collections, so we must master the methods of traversing collections proficiently.

Here we don't talk about for loop traversal. The for loop cannot traverse the set sub-collection of a single-column collection, because the set collection is characterized by disorder and cannot be traversed by index.

How to traverse a single-column collection:

The iterator traverses:

In ES6, in order to facilitate the traversal of the collection data structure, the Iterable protocol (Iterable protocol) and the Iterator protocol (Iterator protocol) were introduced . Together, these two protocols implement the ability to traverse collections.

The iterable protocol specifies that the collection must implement a method named [Symbol.iterator], which returns an iterator object. The iterator object defines a next() method, which returns an object containing value and done attributes, value indicates the current value, and done attribute indicates whether the current traversal is complete.

There are some built-in iterable objects in JavaScript, such as array (Array), Set, Map, string (String) and arguments, etc. According to the specification of the iterable protocol, these collection objects must implement the [Symbol.iterator] method and return an object conforming to the specification of the iterator protocol.

Commonly used iterator methods:

  1. next(): returns an object containing value and done attributes, value indicates the value of the current traversal, and done indicates whether the traversal has ended.

  2. return(): used to end the iteration early, and then return an object containing value and done attributes, value indicates the return value at the end of early, and the done attribute is true.

  3. throw(): It is used to actively throw an exception, which is used to abort the traversal when an error or exception is encountered during the iteration.

case:

import java.util.Iterator;

public class text05 {
    public static void main(String[] args) {
        String list="abide";
        Iterator<String> it=list.lines().iterator();
        String str=it.next();
        System.out.println(str);
    }
}

In this Java code, `list` is a string variable, the `lines()` method is called and the `iterator()` method converts it into an iterator object corresponding to a string array, and the iterator object is assigned to the `it` variable. The `it.next()` method gets the next element in the iterator, which is the first element in the string array, and assigns it to the `str` variable. Finally print the value of the `str` variable to the console.

Because there is only one string "abide" in the list variable, list.lines() returns a string array ["abide"] containing only one element, and because the iterator() method is called, the iterator object of the corresponding array is obtained. So the printed result is "abide".

In addition to arrays, other collection objects such as Set, Map, and strings can also be traversed using iterators.

Although iterators can quickly point to elements in the container, we cannot simply think of iterators as pointers.

In Java, an iterator is an object that allows us to iterate over the elements in a container such as a collection or a list. The essence of iterators is to provide a general method so that we can access the internal elements of the collection class without exposing the implementation details inside the container. This feature allows us to traverse different types of containers in the same way while maintaining the encapsulation of the container class.

The essence of an iterator includes two aspects. One is to be able to access the elements inside the container, and the other is to be able to support operations such as moving forward, moving backward, and deleting. In a specific implementation, the iterator usually holds a reference to the container object, and provides methods such as next(), hasNext(), remove(), etc. to implement element access and control operations. In addition, Java iterators also have some important features, such as fast failure mechanism, support for concurrent access, etc., to ensure the correctness and reliability of the program.

Enhanced for traversal:

The enhanced for loop in Java is a syntax that simplifies iterating over an array or collection. It can iterate over each element in a loop without explicitly defining a loop counter or iterator. Here is the sample code:

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}

This code creates an array of integers and then uses an enhanced for loop to iterate through the array. On each loop iteration, the enhanced for loop will take an element from the array and store it in a variable named number.

In fact, the bottom layer of the enhanced for loop is the iterator, which we created to simplify the code writing of the iterator. 

The enhanced for loop in Java can be used to traverse any collection object that implements the Iterable interface.

case:

List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
for (String name : names) {
    System.out.println(name);
}

This code creates a list of strings and uses an enhanced for loop to iterate through each element in the list.

It should be noted that the enhanced for loop is only used for traversal operations, it cannot be used to modify the elements in the collection. If you need to modify the elements in the collection in the loop, you should use the traditional `for` loop or iterator to traverse.

Enhanced for loop features:

1. Concise and easy to read : Enhancing the for loop can make the code more concise and easy to read, especially when traversing container types such as arrays or collections, cumbersome operations such as indexing or iterators can be omitted.

2. Security : The enhanced for loop is a type-safe loop, that is, the type matching can be checked at compile time, thus avoiding type conversion errors at runtime.

3. Inefficiency : Although the enhanced for loop is concise and easy to read, in some scenarios with high performance requirements, its efficiency may be lower than the traditional for loop or iterator traversal. This is because the enhanced for loop needs to perform an array or collection object access operation in each loop iteration, resulting in some additional performance loss.

In general, the enhanced for loop is suitable for those simple traversal operations, which can improve code readability and maintainability. But for complex traversal scenarios, traditional for loops or iterators should be used to implement traversal.

The lambda method traverses: 

Lambda is a new feature introduced by Java 8 , which can simplify the use of anonymous classes and make the code more concise and easy to read. Lambda expressions can be passed as method parameters, similar to passing a function or code block, which can greatly reduce the complexity of code and API . Here is a sample code for Lambda:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.forEach((n) -> System.out.println(n));

This code creates a list of integers, then uses the forEach method to iterate through the list and print out each element. Here, we use a Lambda expression (n) -> System.out.println(n)  as the parameter of the forEach method , where `(n)` is the formal parameter list of the Lambda expression, `->` is the Lambda operator, and `System.out.println(n)` is the function body of the Lambda expression .

In this example, the lambda expression can be understood as a simple anonymous function that takes an integer parameter `n` and prints it out. Compared with traditional anonymous classes, using Lambda expressions can make the code more concise and clear, while avoiding the performance and memory overhead caused by creating additional anonymous class objects.

In addition to the forEach method, Lambda expressions can be used with any method that accepts a functional interface as an argument, for example:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().mapToInt(n -> n).sum();
System.out.println(sum);

This code uses Java 8's streaming API, converts a list of integers to a stream and calls the `mapToInt` method to convert each element to an integer type and sum. Here, `(n -> n)` represents a simple Lambda expression that takes an integer parameter and returns itself.

Features of Lambda expressions:

1. Concise and easy to read: Lambda expressions can significantly simplify the syntax of anonymous classes , making the code more concise and easy to read.

2. Passing behavior: Lambda expression can be regarded as a way of passing behavior. It can be passed as a method parameter, thus providing a flexible and reusable code block.

3. Efficiency: Lambda expressions can improve code efficiency and performance, especially in scenarios such as concurrency or collection processing, which can save time and memory overhead.

4. Type deduction: The type deduction mechanism introduced by Java 8 enables Lambda expressions to omit parameter types in some cases and reduce code redundancy.

5. Closure and variable capture: Lambda expressions can capture variables within code blocks to form closures. This allows Lambda expressions to access state such as local variables and object fields, enabling more flexible and powerful behavior.

In short, Lambda expression in Java is a convenient, efficient, and flexible programming method, which can realize code reuse and flexible combination in many scenarios. Its use can improve the readability and maintainability of the code, but also reduce the complexity and error rate of the code.

Summarize:

        We must master the first two traversal methods for single-column collections, and the last lambda can be mastered selectively. There are many methods for traversing single-column collections. Here we just introduce a few of the most commonly used traversal methods.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

69e9169c980f43e0aad31ff9ada88a9c.png

Guess you like

Origin blog.csdn.net/fckbb/article/details/131409058