【问题标题】:How to convert List of Double to List of String?如何将 Double 列表转换为字符串列表?
【发布时间】:2011-06-02 11:15:12
【问题描述】:

这对你们所有人来说可能太容易了,但我只是在一个项目中学习和实现 Java,并且坚持这样做。

如何将DoubleList转换为ListString

【问题讨论】:

    标签: java string list double


    【解决方案1】:

    有很多方法可以做到这一点,但这里有两种样式供您选择:

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

    【讨论】:

    • 谢谢我用了第一种方法!
    【解决方案2】:

    您必须遍历您的双重列表并添加到新的字符串列表中。

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

    【讨论】:

    • 感谢托马斯!你们所有人基本上都指向了相同的方法.. 非常感谢
    【解决方案3】:
    List<Double> ds = new ArrayList<Double>();
    // fill ds with Doubles
    List<String> strings = ds.stream().map(op -> op.toString()).collect(Collectors.toList());
    

    【讨论】:

      【解决方案4】:
      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());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        相关资源
        最近更新 更多