简体   繁体   English

如何将 Double 列表转换为字符串列表?

[英]How to convert List of Double to List of String?

This just might be too easy for all of you, but I am just learning and implementing Java in a project and am stuck with this.这对你们所有人来说可能太容易了,但我只是在一个项目中学习和实施 Java 并坚持这一点。

How to convert List of Double to List String ?如何将Double List转换为List String

There are many ways to do this but here are two styles for you to choose from:有很多方法可以做到这一点,但这里有两个 styles 供您选择:

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());
}

But a cooler way to do this is to use a modern collections API (my favourite is Guava ) and do this in a more functional style:但更酷的方法是使用现代 collections API (我最喜欢的是Guava )并以更实用的风格执行此操作:

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

You have to iterate over your double list and add to a new list of strings.您必须遍历您的双重列表并添加到新的字符串列表中。

List<String> stringList = new LinkedList<String>();
for(Double d : YOUR_DOUBLE_LIST){
   stringList.add(d.toString());
}
return stringList;
List<Double> ds = new ArrayList<Double>();
// fill ds with Doubles
List<String> strings = ds.stream().map(op -> op.toString()).collect(Collectors.toList());
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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM