如何将Double列表转换为String列表?

8

这可能对你们所有人来说都太简单了,但我正在学习并在项目中实现Java,目前遇到了困难。

如何将List中的Double转换为ListString

4个回答

10

有很多种方法可以实现这个功能,但以下是两种可供选择的方式:

List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = new ArrayList<String>();
for (Double d : ds) {
    // Apply formatting to the string if necessary
    strings.add(d.toString());
}

但是更酷的方式是使用现代集合API(我最喜欢的是Guava),用更函数式的方式来实现:

List<String> strings = Lists.transform(ds, new Function<Double, String>() {
        @Override
        public String apply(Double from) {
            return from.toString();
        }
    });

谢谢,我使用了第一种方法! - Rasmus

6

您需要遍历双重列表并将其添加到一个新的字符串列表中。

List<String> stringList = new LinkedList<String>();
for(Double d : YOUR_DOUBLE_LIST){
   stringList.add(d.toString());
}
return stringList;

谢谢Thomas!你们所有人基本上都指出了同样的方法..非常感谢 - Rasmus

5
List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = ds.stream().map(op -> op.toString()).collect(Collectors.toList());

1
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.1d);
doubleList.add(2.2d);
doubleList.add(3.3d);

List<String> listOfStrings = new ArrayList<String>();
for (Double d:doubleList)
     listOfStrings.add(d.toString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接