SoFunction
Updated on 2025-04-07

Introduction to List in Java, common methods and five traversal methods.

Introduction to Java List

In Java,ListAn interface is part of the collection framework that defines an ordered collection that allows the storage of duplicate elements and can be accessed through the index.ListInherited fromCollectionInterface, provides additional functionality to handle ordered collections.ListThe main features include:

  • Orderful: The order of accessing elements is consistent with the order during insertion.
  • Repeatability: Allows to store duplicate elements.
  • Index access: Elements can be accessed and manipulated through integer indexes.

CommonListImplementation class hasArrayListLinkedListVectorandStackwait. in,ArrayListBased on dynamic array implementation, suitable for frequent random access;LinkedListBased on the bidirectional linked list, it is more suitable for frequent insertion and deletion operations.

List common methods

The following isListSome common methods and example codes for interfaces:

  • Add elements

    • add(E e): Add an element to the end of the list.
    • add(int index, E element): Insert an element at the specified position, and the original element will move backwards.
    • addAll(Collection<? extends E> c): Add all elements in the specified collection to the end of the list in order.
    • addAll(int index, Collection<? extends E> c): Starting from the specified location, insert all elements in the specified collection into the list.
    import ;
    import ;
    
    public class ListAddExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            (1, "Orange"); // Insert "Orange" at index 1        ("After adding elements: " + list);
    
            List&lt;String&gt; moreFruits = new ArrayList&lt;&gt;();
            ("Grape");
            ("Peach");
            (moreFruits); // Add to the end        (1, moreFruits); //Add from index 1        ("After adding all elements: " + list);
        }
    }
    
  • Get elements

    • get(int index): Returns the element at the specified position in the list.
    • indexOf(Object o): Returns the index of the specified element that appears for the first time; if not found, return -1.
    • lastIndexOf(Object o): Returns the index of the specified element that appeared last; if not found, returns -1.
    import ;
    import ;
    
    public class ListGetExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            String fruit = (1); // Get the element at index 1        ("Element at index 1: " + fruit);
    
            int index = ("Orange"); // Find the index of "Orange"        ("Index of 'Orange': " + index);
    
            int lastIndex = ("Banana"); // Find the last "Banana" index        ("Last index of 'Banana': " + lastIndex);
        }
    }
    
  • Modify elements

    • set(int index, E element): Replace elements at the specified position in the list with the specified element and return the replaced element.
    import ;
    import ;
    
    public class ListSetExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            String oldFruit = (1, "Grape"); // Modify the element at index 1        ("Replaced element: " + oldFruit);
            ("Updated list: " + list);
        }
    }
    
  • Delete elements

    • remove(int index): Removes the element at the specified position in the list and returns the removed element.
    • remove(Object o): Removes the first occurrence of the specified element in the list (only if it exists), and returnstrue, otherwise returnfalse
    import ;
    import ;
    
    public class ListRemoveExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            String removedFruit = (1); // Remove the element at index 1        ("Removed element: " + removedFruit);
            ("Updated list: " + list);
    
            boolean isRemoved = ("Apple"); // Remove the first "Apple"        ("Is 'Apple' removed? " + isRemoved);
            ("Final list: " + list);
        }
    }
    
  • Query elements

    • contains(Object o): If the list contains the specified element, returntrue
    • isEmpty(): If the list does not contain any elements, returntrue
    import ;
    import ;
    
    public class ListQueryExample {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            ("Apple");
            ("Banana");
            ("Orange");
    
            boolean containsBanana = ("Banana");
            ("Does the list contain 'Banana'? " + containsBanana);
    
            boolean isEmpty = ();
            ("Is the list empty? " + isEmpty);
        }
    }
    
  • Other operations

    • clear(): Remove all elements from the list.
    • size(): Returns the number of elements in the list.
    • iterator(): Returns an iterator for iterating through elements in the list.
    • listIterator(): Return oneListIterator, can traverse the list in both directions and support adding or removing elements during the traversal.
    import ;
    import ;
    import ;
    import ;
    
    public class ListOtherOperationsExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            ("List size: " + ());
    
            Iterator&lt;String&gt; iterator = ();
            while (()) {
                ("Iterator: " + ());
            }
    
            ListIterator&lt;String&gt; listIterator = ();
            while (()) {
                ("ListIterator forward: " + ());
            }
            while (()) {
                ("ListIterator backward: " + ());
            }
    
            (); // Clear the list        ("Is the list empty after clearing? " + ());
        }
    }
    

Five ways to traverse

  • Iterator

    • useIteratorThe interface provideshasNext()andnext()Method to iterate over the list. This approach is suitable for situations where elements need to be removed during traversal, becauseIteratorProvides the ability to remove elements safely, avoidingConcurrentModificationExceptionrisk.
    import ;
    import ;
    import ;
    
    public class IteratorTraversalExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            Iterator&lt;String&gt; iterator = ();
            while (()) {
                String item = ();
                (item);
                if ("Banana".equals(item)) {
                    (); // Safely remove the current element            }
            }
            ("List after removal: " + list);
        }
    }
    
  • Enhanced for loop

    • Enhanced for loops (also known as foreach loops) provide a cleaner way to traverseList, no need to explicitly manage indexes. The code is clearer and easier to read, suitable for scenarios where index information is not required.
    import ;
    import ;
    
    public class EnhancedForLoopTraversalExample {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            ("Apple");
            ("Banana");
            ("Orange");
    
            for (String item : list) {
                (item);
            }
        }
    }
    
  • Normal for loop

    • Using traditional for loops is traversalListOne of the most direct ways. This method allows you to access elements in the list through the index, which is suitable for situations where you need to know the current element position or need to operate based on the index.
    import ;
    import ;
    
    public class ForLoopTraversalExample {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            ("Apple");
            ("Banana");
            ("Orange");
    
            for (int i = 0; i < (); i++) {
                ("Index " + i + ": " + (i));
            }
        }
    }
    
  • Stream API(Java 8+)

    • Introduced since Java 8StreamThe API provides powerful functions for collection operations, including but not limited to filtering, mapping, sorting, etc. It allows for the writing of complex collection operation logic in a declarative manner and can be easily converted into parallel streams, thereby leveraging the advantages of multi-core processors to speed up processing speeds.
    import ;
    import ;
    
    public class StreamApiTraversalExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            ().forEach(::println); // Single threaded traversal        // Or use parallel streams        // ().forEach(::println);
        }
    }
    
  • List Iterator (ListIterator)

    • ListIteratoryesIteratora subinterface forListgather. Not only does it support bidirectional traversal (forward and backward), it can also add or delete elements during the traversal. This makesListIteratorVery useful in certain scenarios.
    import ;
    import ;
    import ;
    
    public class ListIteratorTraversalExample {
        public static void main(String[] args) {
            List&lt;String&gt; list = new ArrayList&lt;&gt;();
            ("Apple");
            ("Banana");
            ("Orange");
    
            ListIterator&lt;String&gt; listIterator = ();
            while (()) {
                String item = ();
                ("Forward: " + item);
                if ("Banana".equals(item)) {
                    ("Grape"); // Add new element after the current element            }
            }
            ("List after addition: " + list);
    
            while (()) {
                String item = ();
                ("Backward: " + item);
                if ("Banana".equals(item)) {
                    (); // Remove the current element            }
            }
            ("List after removal: " + list);
        }
    }
    

Summarize

ListInterfaces and common implementation classes such asArrayListandLinkedListIt is an indispensable part of Java programming and provides rich APIs to handle ordered collections. Through understandingListThe characteristics and common methods, and mastering five traversal methods, developers can choose the most appropriate way to operate according to specific needs.Listgather. Whether it is simple traversal or complex collection operations, Java provides flexible and efficient solutions.

This is the article about the introduction of List in Java, common methods and five traversal methods. For more information about common methods and traversal methods of Java List, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!