Java List Last Item addDelimiter(List lines, String delimiter, boolean isDelimitedLastLine)

Here you can find the source of addDelimiter(List lines, String delimiter, boolean isDelimitedLastLine)

Description

add Delimiter

License

Apache License

Parameter

Parameter Description
lines a parameter
delimiter a parameter
isDelimitedLastLine a parameter

Return

Given lines ending with given delimiter, optionally also the last line

Declaration

public static List<String> addDelimiter(List<String> lines, String delimiter, boolean isDelimitedLastLine) 

Method Source Code


//package com.java2s;
/*//from ww w. j a  v  a  2  s  . c  o m
 * Copyright 2011-2015 Kay Stenschke
 *
 * 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.List;

public class Main {
    /**
     * @param   lines
     * @param   delimiter
     * @param   isDelimitedLastLine
     * @return  Given lines ending with given delimiter, optionally also the last line
     */
    public static List<String> addDelimiter(List<String> lines, String delimiter, boolean isDelimitedLastLine) {
        int amountLines = lines.size();
        int index = 0;

        for (String line : lines) {
            line = line.trim();

            boolean isLastLine = index + 1 == amountLines;

            if (!isLastLine || isDelimitedLastLine) {
                // Add delimiter to all lines
                if (!line.endsWith(delimiter)) {
                    line = line + delimiter;
                }
            }

            if (isLastLine && !isDelimitedLastLine && line.endsWith(delimiter)) {
                // Optional: remove delimiter from last line
                line = line.substring(0, line.length() - 1);
            }

            lines.set(index, line + "\n");
            index++;
        }

        return lines;
    }
}

Related

  1. addLast(T e, List list)
  2. addLastElement(List list, T element)
  3. buildPathFromComponentsUpToIndex(final List pathComponents, final int lastIndex)
  4. flattenByteSegments(List byteSegments, int eachSegmentButLastLength, int lastSegmentLength)