Home > Mobile >  How to add on last string comma in list?
How to add on last string comma in list?

Time:11-10

I have this part of code:

 if (CollectionUtils.isNotEmpty(itemAttValues)) {
            return String.join(";", itemAttValues);
        }

and i get this : 9000;9001 but what i want is 9000;9001; so on last string to add ; also.

Any suggestion?

CodePudding user response:

I don't know if you are working with an array or a ArrayList/List.

For an array:

if (CollectionUtils.isNotEmpty(itemAttValues)) {
    if (intemAttVallues.legnth != 1) {
        return String.join(";", itemAttValues)   ";";
       }
    return itemAttValues[0]   ";";
    }

For a ArrayList/List:

if (CollectionUtils.isNotEmpty(itemAttValues)) {
    if (intemAttVallues.size() != 1) {
        return = String.join(";", itemAttValues)   ";";
       }
    return itemAttValues.get(0)   ";";
    }

CodePudding user response:

If you are using JDK 1.8, you can use the java.util.stream.Stream combined with the java.util.StringJoiner as follows:

if (CollectionUtils.isNotEmpty(itemAttValues)) {
    return itemAttValues.stream()
        .collect(() -> new StringJoiner(";", "", ";"), StringJoiner::add, StringJoiner::merge)
        .toString();
}

EDIT (per @saka1029 deleted shortcut):

You can use the Collectors#joining utility collector directly:

if (CollectionUtils.isNotEmpty(itemAttValues)) {
    return itemAttValues.stream()
        .collect(Collectors.joining(";", "", ";"))
        .toString();
}

CodePudding user response:

The way I’d describe your requirement is that you want a semicolon after each value rather than just semicolons between them. The separator that a join operation can use is for putting a separator only between the values, so I don’t want to use that one. I prefer to make explicit that I put a semicolon after each value:

    List<String> itemAttValues = List.of("9000", "9001");
    String joined = itemAttValues.stream()
            .map(v -> v   ';')
            .collect(Collectors.joining());
    System.out.println(joined);

Output:

9000;9001;

A good old loop with a StringBuilder can obtain the same (left for the reader).

Edit: if your list has got just a single value, we get a semicolon after that too (not two):

    List<String> itemAttValues = List.of("9002");

9002;

CodePudding user response:

You can use Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix).

Demo:

import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> itemAttValues = List.of("9000", "9001");
        String joined = itemAttValues.stream()
                            .collect(Collectors.joining(";", "", ";"));
        System.out.println(joined);
    }
}

Output:

9000;9001;
  •  Tags:  
  • java
  • Related