杰瑞科技汇

java join array

Of course! In Java, there are several ways to join elements from an array or a collection into a single string. The best method depends on your specific needs, such as performance, simplicity, and whether you're using modern Java (Java 8+).

java join array-图1
(图片来源网络,侵删)

Here are the most common and effective methods, ordered from most recommended to older/alternative approaches.


The Modern Java 8+ Way: String.join()

This is the most concise and readable approach if you are using Java 8 or later. It's perfect for joining elements from a Collection (like a List or Set) or an array of strings.

For a Collection (e.g., List, Set)

This is the primary use case for String.join().

import java.util.Arrays;
import java.util.List;
public class StringJoinExample {
    public static void main(String[] args) {
        // 1. Using a List of Strings
        List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
        // Join with a comma and a space as the delimiter
        String result1 = String.join(", ", fruits);
        System.out.println("Joined List: " + result1);
        // Output: Joined List: Apple, Banana, Cherry
        // Join with a different delimiter
        String result2 = String.join(" | ", fruits);
        System.out.println("Joined with '|': " + result2);
        // Output: Joined with '|': Apple | Banana | Cherry
    }
}

For an Array of Strings

The String.join() method also has a static overload that takes a String[] directly.

java join array-图2
(图片来源网络,侵删)
import java.util.Arrays;
public class StringJoinArrayExample {
    public static void main(String[] args) {
        // 2. Using an array of Strings
        String[] cities = {"New York", "London", "Tokyo"};
        String result = String.join(" - ", cities);
        System.out.println("Joined Array: " + result);
        // Output: Joined Array: New York - London - Tokyo
    }
}

Important Note: String.join() only works for an array of String. If you have an array of other types (e.g., Integer, Double), it will not compile. You'll need to convert them to strings first (see Method 3 for how to do this easily).


The Classic Way: StringBuilder (or StringBuffer)

This method works in all versions of Java and is the most performant for joining a large number of elements. It avoids creating many intermediate String objects in memory.

This approach is ideal when you have an array of non-string objects or when you need maximum performance in a loop.

public class StringBuilderExample {
    public static void main(String[] args) {
        String[] techs = {"Java", "Spring", "Hibernate"};
        String delimiter = ", ";
        StringBuilder sb = new StringBuilder();
        // Loop through the array
        for (int i = 0; i < techs.length; i++) {
            // Append the current element
            sb.append(techs[i]);
            // Append the delimiter if it's not the last element
            if (i < techs.length - 1) {
                sb.append(delimiter);
            }
        }
        String result = sb.toString();
        System.out.println("Joined with StringBuilder: " + result);
        // Output: Joined with StringBuilder: Java, Spring, Hibernate
    }
}

Pros:

java join array-图3
(图片来源网络,侵删)
  • Very fast and memory-efficient.
  • Works with any type of array (just call .toString() on each element).
  • Universal (works in all Java versions).

Cons:

  • More verbose than String.join().
  • Requires manual logic to avoid adding a delimiter at the end.

The Flexible Way: Java 8 Streams

If you need to join an array of non-string objects or want more complex joining logic, Java 8 Streams are an excellent and powerful choice.

You can use the Collectors.joining() method, which is the stream equivalent of String.join().

import java.util.Arrays;
import java.util.stream.Collectors;
public class StreamJoinExample {
    public static void main(String[] args) {
        // Joining an array of Integers
        Integer[] numbers = {1, 2, 3, 4, 5};
        // Use a stream to map each Integer to a String, then join
        String result1 = Arrays.stream(numbers)
                               .map(Object::toString) // Or .map(String::valueOf)
                               .collect(Collectors.joining(", "));
        System.out.println("Joined Integers: " + result1);
        // Output: Joined Integers: 1, 2, 3, 4, 5
        // Joining an array of custom objects
        Person[] people = {
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        };
        String result2 = Arrays.stream(people)
                               .map(Person::getName) // Get the name property
                               .collect(Collectors.joining(" and "));
        System.out.println("Joined Person Names: " + result2);
        // Output: Joined Person Names: Alice and Bob and Charlie
    }
    static class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
    }
}

Pros:

  • Extremely flexible. Can handle any object type.
  • Allows for complex transformations (e.g., extracting a property from an object).
  • Can be combined with other stream operations (filter, sort, etc.).

Cons:

  • Slightly more verbose than String.join() for simple string arrays.
  • Requires Java 8+.

The Old Way: Manual Loop

This is the pre-Java 8, pre-StringBuilder approach. It's simple but not recommended for new code because it's inefficient due to creating many intermediate String objects.

public class ManualLoopExample {
    public static void main(String[] args) {
        String[] words = {"Hello", "World", "From", "Java"};
        String delimiter = " ";
        String result = "";
        for (String word : words) {
            if (!result.isEmpty()) {
                result += delimiter; // Add delimiter if result is not empty
            }
            result += word;
        }
        System.out.println("Joined with Manual Loop: " + result);
        // Output: Joined with Manual Loop: Hello World From Java
    }
}

Why it's not recommended: The line result += word effectively creates a new String object in every iteration of the loop. For large arrays, this can be very slow and consume a lot of memory.


Summary and Recommendation

Method Best For Java Version Pros Cons
String.join() Joining String arrays or Collections. Java 8+ Most concise and readable. Only works for strings.
StringBuilder Maximum performance or joining non-string arrays. All versions Fast, memory-efficient, universal. Verbose, manual logic.
Streams + Collectors.joining() Flexibility. Joining non-strings, complex transformations. Java 8+ Very powerful and flexible. Slightly more verbose for simple cases.
Manual Loop Learning the basics. All versions Simple concept. Inefficient (do not use in production).

Final Recommendation:

  • If you have a String array or List and are using Java 8+, use String.join(). It's the cleanest and most idiomatic solution.
  • If you have an array of non-string objects (e.g., Integer, Double, custom objects), use Java 8 Streams with Collectors.joining().
  • If you are on an older Java version (< 8) or need absolute maximum performance in a tight loop, use StringBuilder.
分享:
扫描分享到社交APP
上一篇
下一篇