杰瑞科技汇

Java中String的List如何高效操作?

Of course! In Java, the combination of a List and a String is one of the most common and fundamental operations. You'll often find yourself needing to store a collection of strings, perform searches, or manipulate them.

Java中String的List如何高效操作?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything from basic usage to advanced topics.


The Core Concept: List<String>

In Java, List is an interface that represents an ordered collection (also known as a sequence). It allows you to store elements, including strings, in a specific order. The elements can be accessed by their integer index (position in the list).

Because List is an interface, you cannot create an instance of it directly. You must use one of its concrete implementations. The three most common are:

Implementation Description When to Use
ArrayList<String> A resizable-array implementation. It's the most common choice. Excellent for general-purpose use. Offers very fast random access (get by index) but can be slower when adding/removing elements from the middle of the list.
LinkedList<String> Implements a doubly-linked list. Good for frequent insertions and deletions at both ends of the list. Slower for random access than ArrayList.
Vector<String> A legacy class, similar to ArrayList but synchronized. Generally avoided in modern code unless you need thread-safe operations without external synchronization. CopyOnWriteArrayList is a better alternative for thread-safe lists.

Best Practice: Always program to the interface (List) unless you have a specific reason to use the implementation class (ArrayList).

Java中String的List如何高效操作?-图2
(图片来源网络,侵删)
// Good: Programming to the interface
List<String> names = new ArrayList<>();
// Also fine, but less flexible if you want to change the implementation later
ArrayList<String> names = new ArrayList<>();

How to Create and Initialize a List<String>

a. Empty List

This creates an empty list that can grow as you add elements.

import java.util.ArrayList;
import java.util.List;
List<String> fruits = new ArrayList<>();

b. Pre-filled List (Java 9+)

This is the most modern and concise way to create a list with initial elements.

import java.util.List;
// Create an immutable list with 3 elements
List<String> colors = List.of("Red", "Green", "Blue");
// Important: This list is UNMODIFIABLE!
// colors.add("Yellow"); // This will throw an UnsupportedOperationException

c. Pre-filled List (Older Java versions)

Before Java 9, you had to use more verbose methods.

import java.util.Arrays;
import java.util.List;
// Method 1: Using Arrays.asList() - returns a fixed-size list
List<String> planets = Arrays.asList("Mercury", "Venus", "Earth");
// planets.add("Mars"); // This will throw an UnsupportedOperationException!
// Method 2: Create an empty list and addAll (the classic way)
List<String> animals = new ArrayList<>();
animals.addAll(Arrays.asList("Lion", "Tiger", "Bear"));

Common Operations on a List<String>

Here are the essential methods you'll use every day.

Java中String的List如何高效操作?-图3
(图片来源网络,侵删)

Adding Elements

  • add(E element): Appends an element to the end of the list.
  • add(int index, E element): Inserts an element at a specific position.
List<String> programmingLanguages = new ArrayList<>();
programmingLanguages.add("Java");
programmingLanguages.add("Python");
programmingLanguages.add(1, "JavaScript"); // Insert at index 1
// Result: ["Java", "JavaScript", "Python"]
System.out.println(programmingLanguages);

Accessing Elements

  • get(int index): Retrieves the element at the specified index.
List<String> names = List.of("Alice", "Bob", "Charlie");
String secondName = names.get(1); // "Bob"
System.out.println("The second name is: " + secondName);

Updating Elements

  • set(int index, E element): Replaces the element at the specified index with a new one.
List<String> tasks = new ArrayList<>(List.of("Buy milk", "Walk dog", "Pay bills"));
tasks.set(0, "Buy coffee"); // Replace "Buy milk" with "Buy coffee"
// Result: ["Buy coffee", "Walk dog", "Pay bills"]
System.out.println(tasks);

Removing Elements

  • remove(int index): Removes the element at the specified index.
  • remove(Object element): Removes the first occurrence of the specified element.
List<String> cities = new ArrayList<>(List.of("New York", "London", "Paris", "London"));
// Remove by index
cities.remove(0); // Removes "New York"
// Remove by element
cities.remove("London"); // Removes the first "London"
// Result: ["Paris", "London"]
System.out.println(cities);

Checking Size and Emptiness

  • size(): Returns the number of elements in the list.
  • isEmpty(): Returns true if the list contains no elements.
List<String> emptyList = new ArrayList<>();
System.out.println("Is empty? " + emptyList.isEmpty()); // true
System.out.println("Size: " + emptyList.size());      // 0
emptyList.add("Hello");
System.out.println("Is empty? " + emptyList.isEmpty()); // false
System.out.println("Size: " + emptyList.size());      // 1

Iterating (Looping Through) a List

There are several ways to loop over a List<String>.

Enhanced For-Loop (Most Common)

List<String> languages = List.of("Java", "C++", "Python", "Go");
for (String language : languages) {
    System.out.println(language);
}

Using an Iterator Useful when you need to remove elements while iterating.

List<String> items = new ArrayList<>(List.of("A", "B", "C", "D"));
Iterator<String> iterator = items.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("B")) {
        iterator.remove(); // Safe removal
    }
}
// Result: ["A", "C", "D"]
System.out.println(items);

Using Java 8 Streams (Modern & Powerful) Great for processing data (filtering, mapping, etc.).

List<String> names = List.of("Anna", "Bob", "Charlie", "David");
names.stream()
     .filter(name -> name.startsWith("A")) // Keep names starting with 'A'
     .forEach(System.out::println);        // Print each one
// Output:
// Anna

Searching in a List<String>

  • contains(Object element): Returns true if the list contains the specified element.
  • indexOf(Object element): Returns the index of the first occurrence of the element, or -1 if not found.
  • lastIndexOf(Object element): Returns the index of the last occurrence of the element, or -1 if not found.
List<String> countries = List.of("USA", "Canada", "Mexico", "USA");
boolean hasCanada = countries.contains("Canada"); // true
int index = countries.indexOf("USA");             // 0
int lastIndex = countries.lastIndexOf("USA");    // 3
System.out.println("Index of 'USA': " + index);
System.out.println("Last index of 'USA': " + lastIndex);

Converting a List<String> to an Array

List<String> list = List.of("one", "two", "three");
// Method 1: Create a new array of the same type
String[] array1 = list.toArray(new String[0]);
// Method 2: Let Java determine the type (since Java 11)
String[] array2 = list.toArray(String[]::new);
System.out.println(Arrays.toString(array1)); // [one, two, three]

Sorting a List<String>

You can use the Collections.sort() utility method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
List<String> names = new ArrayList<>(List.of("Charlie", "Anna", "Bob"));
// Sorts the list in natural order (alphabetical for strings)
Collections.sort(names);
// Result: ["Anna", "Bob", "Charlie"]
System.out.println(names);

Complete Example

Here is a full, runnable example that puts many of these concepts together.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ListOfStringExample {
    public static void main(String[] args) {
        // 1. Create and initialize a list
        List<String> todoList = new ArrayList<>();
        todoList.add("Learn Java");
        todoList.add("Read a book");
        todoList.add("Write code");
        todoList.add(1, "Buy groceries"); // Insert an item
        System.out.println("Initial To-Do List: " + todoList);
        // 2. Access an element
        String firstTask = todoList.get(0);
        System.out.println("\nFirst task: " + firstTask);
        // 3. Update an element
        todoList.set(2, "Read a technical book");
        System.out.println("\nAfter updating task #2: " + todoList);
        // 4. Check size and if it's empty
        System.out.println("\nList size: " + todoList.size());
        System.out.println("Is list empty? " + todoList.isEmpty());
        // 5. Search in the list
        boolean hasJava = todoList.contains("Learn Java");
        System.out.println("\nDoes the list contain 'Learn Java'? " + hasJava);
        System.out.println("Index of 'Write code': " + todoList.indexOf("Write code")); // Will be -1 now
        // 6. Iterate through the list
        System.out.println("\n--- Iterating through the list ---");
        for (String task : todoList) {
            System.out.println("- " + task);
        }
        // 7. Remove an element
        todoList.remove("Read a book");
        System.out.println("\nAfter removing 'Read a book': " + todoList);
        // 8. Sort the list
        Collections.sort(todoList);
        System.out.println("\nAfter sorting the list: " + todoList);
    }
}

Key Takeaways

  1. Use List<String> to represent an ordered collection of strings.
  2. Prefer ArrayList<String> for most use cases due to its excellent performance for random access.
  3. Initialize with List.of(...) in modern Java (9+) for simple, immutable lists.
  4. Remember that List.of() creates an immutable list. If you need to add or remove elements, use new ArrayList<>(List.of(...)).
  5. Master the core methods: add(), get(), set(), remove(), size(), contains(), and indexOf().
分享:
扫描分享到社交APP
上一篇
下一篇