The String.join() method in Java provides a convenient way to combine elements of an iterable, such as an ArrayList<Integer>, into a single string with a specified delimiter. Here's how you can use it effectively:

import java.util.ArrayList;
import java.util.stream.Collectors;

public class StringJoinExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // Using String.join() with Java 8 Streams
        String joinedString = numbers.stream()
                .map(Object::toString)
                .collect(Collectors.joining(','));

        System.out.println(joinedString); // Output: 1,2,3
    }
}

Explanation:

  1. Import Necessary Classes:

    • java.util.ArrayList for using the ArrayList class.
    • java.util.stream.Collectors for using the Collectors.joining() method.
  2. Create an ArrayList:

    • An ArrayList<Integer> named 'numbers' is created and populated with integers.
  3. Use String.join() with Streams:

    • We utilize Java 8 Streams for a more concise and efficient way to achieve the desired concatenation.
    • numbers.stream(): Converts the ArrayList into a stream of integers.
    • map(Object::toString): Converts each integer in the stream to its string representation.
    • collect(Collectors.joining(',')): Combines the string elements in the stream, separated by a comma, into a single string.
  4. Print the Result:

    • The 'joinedString' now holds the desired comma-separated string '1,2,3', which is then printed to the console.

This approach provides a clean and readable solution for joining elements of an ArrayList<Integer> into a string using String.join(), especially when combined with Java 8 Streams for improved efficiency and code clarity.

Java String.join() With ArrayList<Integer>: A Complete Guide

原文地址: http://www.cveoy.top/t/topic/fyMW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录