Java List Concatenate concatCsvLine(List values, String fieldSeparator)

Here you can find the source of concatCsvLine(List values, String fieldSeparator)

Description

Basic CSV line concatination with characters escaping

License

Open Source License

Parameter

Parameter Description
values values for concatination
fieldSeparator character for fields separation

Return

concatinated string

Declaration

public static String concatCsvLine(List<String> values,
        String fieldSeparator) 

Method Source Code

//package com.java2s;
import java.util.*;

public class Main {
    /**//w w  w  .  j av a  2s. c o  m
     * Basic CSV line concatination with characters escaping
     *
     * @param values values for concatination
     * @param fieldSeparator character for fields separation
     * @return concatinated string
     */
    public static String concatCsvLine(List<String> values,
            String fieldSeparator) {

        if (values == null || values.isEmpty())
            return null;
        StringBuilder builder = new StringBuilder(escapeStringForCsvFormat(
                values.get(0), fieldSeparator));
        for (int i = 1; i < values.size(); i++) {
            //add separator for 'not last' element
            builder.append(fieldSeparator);
            builder.append(escapeStringForCsvFormat(values.get(i),
                    fieldSeparator));
        }
        return builder.toString();
    }

    private static String escapeStringForCsvFormat(String str,
            String fieldSeparator) {
        if (str == null)
            return "";
        //is escaping fieldSeparators and line separators by quotes needed
        boolean inQuotes = str.indexOf(fieldSeparator) != -1
                || str.indexOf('\n') != -1;
        StringBuilder builder = new StringBuilder();
        if (inQuotes)
            builder.append('\"');
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            //escaping quote by duplicating it
            if (ch == '\"') {
                builder.append('\"');
            }
            builder.append(ch);
        }
        if (inQuotes)
            builder.append('\"');
        return builder.toString();
    }
}

Related

  1. concat(List list, T... items)
  2. concatAddresses(List addresses)
  3. concatAll(final T[] empty, Iterable arrayList)
  4. concatArrays(List arrays, int start, int size)
  5. concatArraysToList(final T[]... arrays)
  6. concateAliases(List aliases)
  7. concatElementsWithBrackets(List input)
  8. concatenate(List aList)
  9. concatenate(List> lists)