2
List<String> solList = new ArrayList<String>( );
solList.add( "num1" );
solList.add( "num2" );

StringBuilder result = new StringBuilder();
for ( String a : solList )
{
result.append( a ).append( ", " );
}

String withoutLastComma = result.substring( 0, result.length( ) - ", 
".length( ) );
System.err.println( withoutLastComma );

I want remove last comma,I use substring,how can I become better this code?

use string utility methods such as "StringUtil.join" to concatenate elements in an array or a collection object. Consult the "StringUtil API's StringUtil.join" entry.

For example: StringUtils.join(["e", "f", "g"], "--") // => "e--f--g

A.lakkantha
  • 121
  • 1
  • 1
  • 12
  • If you just want to add comma's, use a simple for loop with length -2 – Sagar Jun 28 '17 at 04:44
  • 3
    You can do everything with [`String.join`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) – ajb Jun 28 '17 at 04:44
  • You can just do `result.setLength(result.length() - 1)`. Or, rather than using the simple `for` loop, you can get the `solList.iterator()` and loop over it "manually" (`while (iterator.hasNext()) { ...`), and that lets you check within the loop whether there's a next element -- so you can just not add that comma to begin with, if you're at the last element. (Or, as ajb pointed out, use the library call that does this for you.) – yshavit Jun 28 '17 at 04:44
  • TO remove last `, `, do `result.delete(result.length()-2,result.length());` – Jay Smith Jun 28 '17 at 04:45
  • @JaySmith Note that he appended two characters between each element--comma and space--so your code will remove the last space but not the comma. – ajb Jun 28 '17 at 04:46
  • Have a look at `StringJoiner` as an alternative to `StringBuilder` for this case – MadProgrammer Jun 28 '17 at 04:46

3 Answers3

5

Below is one of the way you can get comma separated list:

StringBuilder result = new StringBuilder();
int size = 0;
if(solList!=null && (size=solList.size())>0)
{
   result.append(solList.get(0));
   for ( int i=1;i<size;i++ )
   {
        result.append( ", " ).append(solList.get(i));
    }
 }
Denis
  • 1,219
  • 1
  • 10
  • 15
0

There are a number of ways to accomplish this. Java 8 already provides a join method in String that will join strings in a list or array with a fixed string between each pair of elements.

Here's another way. I'm including this as an answer because it's a useful idiom in other array/list traversal cases not necessarily involving strings and separators:

StringBuilder result = new StringBuilder();
boolean first = true;
for ( String a : solList )
{
    if (!first) {
        result.append(", ");
    }
    result.append(a);
    first = false;
}

I wouldn't use it here, but this pattern comes up in many contexts.

This basically works the same way as denis's answer, just expressed in a slightly different way.

ajb
  • 31,309
  • 3
  • 58
  • 84
0

List to Comma-separated String Using java 8 See the String.join()

Logic 1:

import java.util.Arrays;
import java.util.List;

public class TestApp2 {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("A", "B", "C", "D");

        String result = String.join(",", list);
        System.out.println(result);
    }

}

OutPut:

A,B,C,D

Logic 2:

A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence). For example:

 List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
 String commaSeparatedNumbers = numbers.stream()
     .map(i -> i.toString())
     .collect(Collectors.joining(", "));

OutPut:

1,2,3,4
Sudhakar
  • 3,104
  • 2
  • 27
  • 36