Java List Implode implode(String glue, List list)

Here you can find the source of implode(String glue, List list)

Description

Joins a list of items to a single string using "glue" as separator If the item is null, it will add as empty

License

MIT License

Parameter

Parameter Description
glue separator
list list of elements to be joined
T type of elements

Return

final string after concatenation

Declaration

public static <T> String implode(String glue, List<T> list) 

Method Source Code

//package com.java2s;
/*//from w  w  w. j  a v  a2s  .  c  o  m
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * Adyen Java API Library
 *
 * Copyright (c) 2017 Adyen B.V.
 * This file is open source and available under the MIT license.
 * See the LICENSE file for more info.
 */

import java.util.List;

public class Main {
    /**
     * Joins a list of items to a single string using "glue" as separator
     * If the item is null, it will add as empty
     *
     * @param glue separator
     * @param list list of elements to be joined
     * @param <T> type of elements
     * @return final string after concatenation
     */
    public static <T> String implode(String glue, List<T> list) {
        // list is empty, return empty string
        if (list == null || list.isEmpty()) {
            return "";
        }

        // init the builder
        StringBuilder sb = new StringBuilder();
        boolean addGlue = false;
        // concat each element
        for (T item : list) {
            if (addGlue) {
                sb.append(glue);
            } else {
                addGlue = true;
            }
            if (item != null) {
                sb.append(item);
            }
        }

        // return result
        return sb.toString();
    }
}

Related

  1. implode(List list, String delimiter)
  2. implode(List list, String glue)
  3. implode(List list, String glue)
  4. implode(List strings, String separator)
  5. implode(List tokens, char separator, char escapeCharacter)
  6. implode(String split, List list)
  7. implodeList(final List list, final String glue)