Create formatted string from ArrayList

Consider the following code:

ArrayList<Integer> aList = new ArrayList<Integer>(); aList.add(2134); aList.add(3423); aList.add(4234); aList.add(343); String tmpString = "("; for(int aValue : aList) { tmpString += aValue + ","; } tmpString = (String) tmpString.subSequence(0, tmpString.length()-1) + ")"; System.out.println(tmpString); 

My result is here (2134.3423.4234.343), as expected.

I replace the last comma with the ending) to get the expected result. Is there a better way to do this overall?

+8
java string
source share
7 answers

You can use Commons Lang :

 String tmpString = "(" + StringUtils.join(aList, ",") + ")"; 

Also, if you cannot use external libraries:

 StringBuilder builder = new StringBuilder("("); for (int aValue : aList) builder.append(aValue).append(","); if (aList.size() > 0) builder.deleteCharAt(builder.length() - 1); builder.append(")"); String tmpString = builder.toString(); 
+15
source share

Since Java 8 you can also:

 ArrayList<Integer> intList = new ArrayList<Integer>(); intList.add(2134); intList.add(3423); intList.add(4234); intList.add(343); String prefix = "("; String infix = ", "; String postfix = ")"; StringJoiner joiner = new StringJoiner(infix, prefix, postfix); for (Integer i : intList) joiner.add(i.toString()); System.out.println(joiner.toString()); 
+4
source share

You will need to replace the last comma with ")". But use StringBuilder instead of adding strings together.

+2
source share

How about this from google-guava

 String joinedStr = Joiner.on(",").join(aList); System.out.println("("+JjoinedStr+")"); 
+2
source share

Build Mateusz Java 8 Example, there is an example in StringJoiner JavaDoc that almost does what the OP wants. A little tweaked, it would look like this:

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

If you used Iterator , you can check hasNext() inside your loop to determine if you need to add a comma.

 StringBuilder builder = new StringBuilder(); builder.append("("); for(Iterator<Integer> i=aList.iterator(); i.hasNext();) { builder.append(i.next().toString()); if (i.hasNext()) builder.append(","); } builder.append(")"); 
0
source share
 for(int aValue : aList) { if (aValue != aList.Count - 1) { tmpString += aValue + ","; } else { tmpString += aValue + ")"; } } 

May be,?

-one
source share

Source: https://habr.com/ru/post/650982/


All Articles