如何从ArrayList获取所需的格式

时间:2016-03-04 14:02:17

标签: java

import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class Test {
    final static Logger logger = Logger.getLogger(Test.class);
    private static DecimalFormat decimal_inpoints = new DecimalFormat("0.00");

    public static void main(String args[]) throws UnknownHostException,
            ParseException {

        ArrayList<Integer> array_list = new ArrayList<Integer>();

        array_list.add(1);
        array_list.add(0);

        String joinedString = array_list.toString();

        System.out.println(joinedString);

    }

}

如何将输出设为1,0

当我使用array_list.toString();它的输出为[1,0](添加了数组)

你能否告诉我如何获得1,0而不是[1,0]

6 个答案:

答案 0 :(得分:6)

使用Apache Commons Lang

String join = StringUtils.join(joinList, ",");

使用Java 8

String joined = String.join(",", list);

使用Google Guava (Joiner)

Joiner joiner = Joiner.on(",");
String join = joiner.join(joinList);

使用StringBuilder

StringBuilder builder = new StringBuilder(array_list.size());
boolean isFirst = true;
for (int i : array_list){
  if (isFirst) {
    builder.append(i);
    isFirst = false;
  } else {
    builder.append(", " + i);
  }
}
System.out.println(builder.toString());

答案 1 :(得分:3)

最简单的方法是;

array_list.toString().replace("[","").replace("]","");

答案 2 :(得分:3)

在Java 8中,您可以使用加入的收集器来执行此操作:

    String joinedString = list.stream()
            .map(Object::toString)
            .collect(Collectors.joining(", "));

答案 3 :(得分:1)

使用Java 8. See here.

private toStringNoBrackets(ArrayList MyList) {
    return String.join(",", MyList);
}

答案 4 :(得分:1)

您可以创建自己的类并覆盖toString方法。

import java.util.ArrayList;

public class MyIntegerArrayList extends ArrayList<Integer>
{
    @Override
    public String toString(){
        return super.toString().replace("[","").replace("]","");
    }
}


MyIntegerArrayList myIntegerArrayList = new MyIntegerArrayList();
myIntegerArrayList.add(0);
myIntegerArrayList.add(1);
myIntegerArrayList.toString();

答案 5 :(得分:0)

使用StringJoiner

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class SOPlayground {

    public static void main(String[] args) {
        List<Integer> array_list = new ArrayList<>();
        array_list.add(1);
        array_list.add(0);

        StringJoiner sj = new StringJoiner(", ");
        array_list.stream().forEach((i) -> {
            sj.add(i.toString());
        });
        System.out.println(sj.toString());
    }

}

输出:

1, 0