Create formatted string from ArrayList

前端 未结 7 877
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 20:11

Consider following code:

    ArrayList aList = new ArrayList();
    aList.add(2134);
    aList.add(3423);
    aList.add(4234);
         


        
相关标签:
7条回答
  • 2021-01-04 20:52
    for(int aValue : aList) {
        if (aValue != aList.Count - 1)
        {
              tmpString += aValue + ",";
        }
        else
        {
              tmpString += aValue + ")";
        }
    }
    

    Perhaps?

    0 讨论(0)
  • 2021-01-04 20:53

    You could use Commons Lang:

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

    Alternatively, if you can't 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();
    
    0 讨论(0)
  • 2021-01-04 20:57

    If you used an Iterator you could test hasNext() inside your loop to determine whether you needed to append 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 讨论(0)
  • 2021-01-04 21:03

    You will have to replace the last comma with a ')'. But use a StringBuilder instead of adding strings together.

    0 讨论(0)
  • 2021-01-04 21:07

    How about this from google-guava

    String joinedStr = Joiner.on(",").join(aList);
    
    System.out.println("("+JjoinedStr+")");
    
    0 讨论(0)
  • 2021-01-04 21:13

    Building off Mateusz's Java 8 example, there's an example in the StringJoiner JavaDoc that nearly does what OP wants. Slightly 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(",","(",")") );
    
    0 讨论(0)
提交回复
热议问题