Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java

JavaJavaBeginner
Pratiquer maintenant

💡 Ce tutoriel est traduit par l'IA à partir de la version anglaise. Pour voir la version originale, vous pouvez cliquer ici

Introduction

In Java programming, manipulating strings and working with collections like ArrayList are essential skills. This tutorial guides you through the process of splitting a string into an ArrayList using a delimiter in Java. By the end of this lab, you will understand how to break down text data into manageable pieces and store them in a flexible collection, enabling you to tackle various data processing tasks in your Java applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/StringManipulationGroup -.-> java/strings("Strings") java/StringManipulationGroup -.-> java/regex("RegEx") java/DataStructuresGroup -.-> java/arrays("Arrays") java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") java/DataStructuresGroup -.-> java/collections_methods("Collections Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("ArrayList") java/SystemandDataProcessingGroup -.-> java/string_methods("String Methods") subgraph Lab Skills java/strings -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/regex -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/arrays -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/arrays_methods -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/collections_methods -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/arraylist -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} java/string_methods -.-> lab-415655{{"Comment diviser une chaîne de caractères en un ArrayList à l'aide d'un délimiteur en Java"}} end

Understanding Strings and ArrayLists in Java

Before we dive into splitting strings, let us understand the two key components we will be working with in this lab.

Strings in Java

A String in Java is a sequence of characters. It is one of the most commonly used classes in Java programming. Strings are immutable, which means once created, their values cannot be changed.

For example:

String greeting = "Hello, World!";

ArrayLists in Java

An ArrayList is a resizable array implementation in Java. Unlike regular arrays that have a fixed size, ArrayLists can grow or shrink dynamically. They are part of the Java Collections Framework and provide various methods to manipulate the stored elements.

To use ArrayList, we need to import it from the java.util package:

import java.util.ArrayList;

Creating an ArrayList:

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");

Now, let us create a new Java file to start working with these concepts. Follow these steps:

  1. Open the WebIDE in your LabEx environment
  2. Navigate to the project directory (it should be open by default)
  3. Create a new file named StringSplitDemo.java by clicking on the "New File" icon in the editor
  4. Add the following basic code to create a simple Java class:
public class StringSplitDemo {
    public static void main(String[] args) {
        // We will add our code here
        System.out.println("String Split Demo");
    }
}
  1. Save the file by pressing Ctrl+S
  2. Open the terminal in the IDE (if not already open) and compile the Java file:
javac StringSplitDemo.java
  1. Run the program:
java StringSplitDemo

You should see the output:

String Split Demo

This confirms that your basic Java setup is working correctly. In the next step, we will learn how to split a string using the split() method.

Splitting Strings Using the split() Method

Java provides a built-in method called split() in the String class that allows us to divide a string into parts based on a delimiter. The method returns an array of strings containing the substrings divided by the delimiter.

The split() Method

The split() method takes a regular expression as a parameter and returns an array of substrings:

String[] split(String regex)

Let us modify our StringSplitDemo.java file to include code that splits a string. Open the file in the editor and update it as follows:

public class StringSplitDemo {
    public static void main(String[] args) {
        // Create a string with comma-separated values
        String csvData = "apple,banana,orange,grape,mango";
        System.out.println("Original string: " + csvData);

        // Split the string using comma as delimiter
        String[] fruits = csvData.split(",");

        // Print the resulting array
        System.out.println("\nAfter splitting:");
        System.out.println("Number of elements: " + fruits.length);

        // Display each element of the array
        for (int i = 0; i < fruits.length; i++) {
            System.out.println("Element " + i + ": " + fruits[i]);
        }
    }
}

Save the file and run the program:

javac StringSplitDemo.java
java StringSplitDemo

You should see output similar to:

Original string: apple,banana,orange,grape,mango

After splitting:
Number of elements: 5
Element 0: apple
Element 1: banana
Element 2: orange
Element 3: grape
Element 4: mango

This demonstrates how the split() method divides the original string at each comma and places each substring into an array. The array fruits now contains five elements, each representing a fruit name from our original comma-separated string.

In the next step, we will convert this array into an ArrayList for more flexibility in manipulating the data.

Converting a Split String to an ArrayList

Now that we have split our string into an array, let us convert it to an ArrayList. ArrayLists offer more flexibility than arrays, including dynamic resizing and convenient methods for adding, removing, and manipulating elements.

Converting an Array to ArrayList

There are several ways to convert an array to an ArrayList in Java:

  1. Using Arrays.asList() and the ArrayList constructor
  2. Using a loop to add each element individually
  3. Using Java 8 Stream API

Let us update our StringSplitDemo.java file to include the conversion to ArrayList. We will need to import the necessary classes from the java.util package:

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

public class StringSplitDemo {
    public static void main(String[] args) {
        // Create a string with comma-separated values
        String csvData = "apple,banana,orange,grape,mango";
        System.out.println("Original string: " + csvData);

        // Split the string using comma as delimiter
        String[] fruits = csvData.split(",");

        // Print the resulting array
        System.out.println("\nAfter splitting into array:");
        System.out.println("Number of elements: " + fruits.length);

        // Display each element of the array
        for (int i = 0; i < fruits.length; i++) {
            System.out.println("Array Element " + i + ": " + fruits[i]);
        }

        // Method 1: Convert to ArrayList using Arrays.asList() and the ArrayList constructor
        ArrayList<String> fruitList1 = new ArrayList<>(Arrays.asList(fruits));

        // Method 2: Convert to ArrayList using a loop
        ArrayList<String> fruitList2 = new ArrayList<>();
        for (String fruit : fruits) {
            fruitList2.add(fruit);
        }

        // Display the ArrayList created using Method 1
        System.out.println("\nAfter converting to ArrayList (Method 1):");
        System.out.println("Number of elements: " + fruitList1.size());

        for (int i = 0; i < fruitList1.size(); i++) {
            System.out.println("ArrayList Element " + i + ": " + fruitList1.get(i));
        }

        // Demonstrate adding a new element to the ArrayList
        fruitList1.add("pineapple");
        System.out.println("\nAfter adding a new element to ArrayList:");
        System.out.println("Number of elements: " + fruitList1.size());
        System.out.println("New element: " + fruitList1.get(fruitList1.size() - 1));
    }
}

Save the file and run the program:

javac StringSplitDemo.java
java StringSplitDemo

You should see output similar to:

Original string: apple,banana,orange,grape,mango

After splitting into array:
Number of elements: 5
Array Element 0: apple
Array Element 1: banana
Array Element 2: orange
Array Element 3: grape
Array Element 4: mango

After converting to ArrayList (Method 1):
Number of elements: 5
ArrayList Element 0: apple
ArrayList Element 1: banana
ArrayList Element 2: orange
ArrayList Element 3: grape
ArrayList Element 4: mango

After adding a new element to ArrayList:
Number of elements: 6
New element: pineapple

This example demonstrates how to convert a string array to an ArrayList and showcases one of the advantages of using an ArrayList: the ability to easily add new elements to the collection.

Note the differences between arrays and ArrayLists:

  • Arrays have a fixed size, while ArrayLists can grow dynamically
  • ArrayLists provide methods like add(), remove(), and get() for manipulating elements
  • ArrayLists can only store objects, not primitive types (though Java automatically handles the conversion using autoboxing)

In the next step, we will explore different delimiters for splitting strings.

Working with Different Delimiters

In the previous steps, we used a comma as our delimiter to split the string. However, the split() method accepts any regular expression as a delimiter, allowing us to split strings based on various patterns.

Let us create a new Java file to experiment with different delimiters. Create a file named DelimiterDemo.java with the following content:

import java.util.ArrayList;
import java.util.Arrays;

public class DelimiterDemo {
    public static void main(String[] args) {
        // 1. Splitting by a single character
        String commaString = "red,green,blue,yellow";
        ArrayList<String> colors = new ArrayList<>(Arrays.asList(commaString.split(",")));

        System.out.println("1. Splitting by comma:");
        for (String color : colors) {
            System.out.println("  " + color);
        }

        // 2. Splitting by space
        String spaceString = "Java Python C++ JavaScript Ruby";
        ArrayList<String> languages = new ArrayList<>(Arrays.asList(spaceString.split(" ")));

        System.out.println("\n2. Splitting by space:");
        for (String language : languages) {
            System.out.println("  " + language);
        }

        // 3. Splitting by multiple characters
        String pipeColonString = "name|John:age|30:city|New York";
        ArrayList<String> personData = new ArrayList<>(Arrays.asList(pipeColonString.split("[|:]")));

        System.out.println("\n3. Splitting by multiple characters (| or :):");
        for (String data : personData) {
            System.out.println("  " + data);
        }

        // 4. Splitting by digits
        String digitsString = "apple123banana456cherry";
        ArrayList<String> fruits = new ArrayList<>(Arrays.asList(digitsString.split("\\d+")));

        System.out.println("\n4. Splitting by digits:");
        for (String fruit : fruits) {
            System.out.println("  " + fruit);
        }

        // 5. Limiting the number of splits
        String limitString = "one-two-three-four-five";
        ArrayList<String> limitedParts = new ArrayList<>(Arrays.asList(limitString.split("-", 3)));

        System.out.println("\n5. Limiting the number of splits (limit=3):");
        for (String part : limitedParts) {
            System.out.println("  " + part);
        }
    }
}

Save the file and run the program:

javac DelimiterDemo.java
java DelimiterDemo

You should see output similar to:

1. Splitting by comma:
  red
  green
  blue
  yellow

2. Splitting by space:
  Java
  Python
  C++
  JavaScript
  Ruby

3. Splitting by multiple characters (| or :):
  name
  John
  age
  30
  city
  New York

4. Splitting by digits:
  apple
  banana
  cherry

5. Limiting the number of splits (limit=3):
  one
  two
  three-four-five

Understanding Different Delimiter Types

  1. Single Character Delimiter: The simplest form, like commas or spaces.

    string.split(",")
  2. Character Class Delimiters: Split by any character in a set.

    string.split("[|:]")  // Split by either '|' or ':'
  3. Regular Expression Delimiters: For more complex patterns.

    string.split("\\d+")  // Split by one or more digits
  4. Limiting Splits: The second parameter limits the number of splits.

    string.split("-", 3)  // Max 3 parts (2 splits)

Special Characters in Regular Expressions

When using regular expressions as delimiters, certain characters have special meanings and must be escaped with a backslash (\). Since the backslash itself needs to be escaped in Java strings, you end up with double backslashes (\\).

Some common special characters:

  • \d - Matches any digit (in Java, write as \\d)
  • \s - Matches any whitespace character (in Java, write as \\s)
  • . - Matches any character (in Java, write as \\.)
  • +, *, ? - Quantifiers (in Java, write as \\+, \\*, \\?)

These examples demonstrate the versatility of the split() method for handling various string formats and requirements in your Java applications.

Summary

In this lab, you have learned how to split strings into ArrayLists using delimiters in Java. You have gained practical experience with:

  • Understanding and working with Strings and ArrayLists in Java
  • Using the split() method to divide strings based on delimiters
  • Converting arrays of strings to ArrayLists for more flexible data manipulation
  • Working with different types of delimiters, including single characters, character classes, and regular expressions
  • Controlling the splitting process with limit parameters

These string manipulation skills are fundamental in Java programming and will help you in various scenarios, including parsing data from files, processing user input, and working with structured text formats like CSV or JSON.

By combining the power of regular expressions with Java collections like ArrayList, you can efficiently process and transform string data to meet the requirements of your applications.