Home > Back-end >  How join strings in the list according to list size
How join strings in the list according to list size

Time:10-22

I want to concatenate strings in List using different delimiters according to list size and element's position.

Here's my code with a sample-data:

final List<String> names = Arrays.asList("Alice","Bob","Kevin");
    
if (names.size() < 3) {
    System.out.println(String.join(" and ", names));
} else {
    String joinedNames = String.join(", ", names.subList(0, names.size() - 1));
    joinedNames  = " and "   names.get(names.size() - 1);
    System.out.println(joinedNames);
}

Expected outputs:

// List of size 2
Alice and Bob

// List of size 3
Alice, Bob and Kevin

Is there a better and more readable way to do it?

CodePudding user response:

There's no way to implement this logic using functional features (at least in a way that could be considered to be well-readable and clean) due to the nature of the task. To join the names properly, we need to be aware of the index of the element (whether it's the last element, or if there's only one element).

But the code you've written might be enhanced a bit:

public static String joinNames(List<String> names) {
    
    if (names.isEmpty()) throw new IllegalArgumentException(); // or return an empty string depending on your needs
    
    StringBuilder result = new StringBuilder();

    if (names.size() > 1) {
        result.append(String.join(", ", names.subList(0, names.size() - 1)))
            .append(" and ");
    }

    return result.append(names.get(names.size() - 1))
        .toString();
}

CodePudding user response:

public static String joinNames(List<String> names) {
    //...
    return String.join(", ", names.toArray(String[]::new)).replaceFirst(", (\\w )$", " and $1");
}

or even better

public static String joinNames(String... names) {
    //...
    return String.join(", ", names).replaceFirst(", (\\w )$", " and $1");
}

CodePudding user response:

You can try in this way using StringBuilder.

Approach Here,

I have first converted the given list of names into , separated string and then replaced the last comma with " and " with the logic below:

sb.lastIndexOf(",") : It will give the index of last , comma in the string, which is used in replacing the last comma separated value. e.g here is ,John with and John

    public class Test {
       public static void main(String[] args) {

        List<String> names = Arrays.asList("Alice","Bob","Kevin","John");
        StringBuilder sb = new StringBuilder();

        if(names.size() > 1) {
            sb.append(String.join(",",names));
            sb.replace(sb.lastIndexOf(","),sb.length()," and "   sb.substring(sb.lastIndexOf(",") 1));
        } else {
            sb.append(names.get(0));
        }
        System.out.println(sb);
    }
}

Output:

Alice,Bob,Kevin and John
  • Related