Java String.join() With ArrayList<Integer>: A Complete Guide
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:
-
Import Necessary Classes:
java.util.ArrayListfor using theArrayListclass.java.util.stream.Collectorsfor using theCollectors.joining()method.
-
Create an ArrayList:
- An
ArrayList<Integer>named 'numbers' is created and populated with integers.
- An
-
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 theArrayListinto 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.
-
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.
原文地址: http://www.cveoy.top/t/topic/fyMW 著作权归作者所有。请勿转载和采集!