Raja Asthana Raja Asthana - 10 months ago 63
Java Question

Convert List of String to List of BigDecimal in java

I'm facing a problem in converting a list of String to list of Bigdecimal in java.

I have a List of String like,

List<String> stringList = new LinkedList<String>();

and BigDecimal List as

List<BigDecimal> bigDecimalList = new LinkedList<BigDecimal>();

Now I want to convert
. I know we can iterate through the
and can add to
new BigDecimal(string)
. Is there any other work around than looping???

Any help is appreciated. Thanks.

Answer Source

Well something's got to loop - and until Java 8 comes with lambda expressions to make it easier to express the conversion, there's no general purpose way of doing the conversion. Obviously you could write a method which took the class name and always passed each element of the incoming list as an argument to the constructor of the target class via reflection, but that would fail in all kinds of other situations.

Given how short the loop is, I'd definitely do that:

List<BigDecimal> bigDecimalList = new LinkedList<BigDecimal>();
for (String value : stringList) {
    bigDecimalList.add(new BigDecimal(value));

Do you really need to avoid those 4 lines of code?