Here you can find the source of join(String separator, Iterable> objects)
Parameter | Description |
---|---|
separator | The string by which to join each string representation |
objects | The objects to join the string representations of |
public static String join(String separator, Iterable<?> objects)
//package com.java2s; /*/*from w w w. j av a 2 s.c o m*/ * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.*; public class Main { /** * Creates a string with {@code toString()} of each object with the given separator. * * <pre> * expect: * join(",", new Object[]{"a"}) == "a" * join(",", new Object[]{"a", "b", "c"}) == "a,b,c" * join(",", new Object[]{}) == "" * </pre> * * The {@code separator} must not be null and {@code objects} must not be null. * * @param separator The string by which to join each string representation * @param objects The objects to join the string representations of * @return The joined string */ public static String join(String separator, Object[] objects) { return join(separator, objects == null ? null : Arrays.asList(objects)); } /** * Creates a string with {@code toString()} of each object with the given separator. * * <pre> * expect: * join(",", ["a"]) == "a" * join(",", ["a", "b", "c"]) == "a,b,c" * join(",", []) == "" * </pre> * * The {@code separator} must not be null and {@code objects} must not be null. * * @param separator The string by which to join each string representation * @param objects The objects to join the string representations of * @return The joined string */ public static String join(String separator, Iterable<?> objects) { if (separator == null) { throw new NullPointerException("The 'separator' cannot be null"); } if (objects == null) { throw new NullPointerException("The 'objects' cannot be null"); } StringBuilder string = new StringBuilder(); Iterator<?> iterator = objects.iterator(); if (iterator.hasNext()) { string.append(iterator.next().toString()); while (iterator.hasNext()) { string.append(separator); string.append(iterator.next().toString()); } } return string.toString(); } }