Raja Asthana Raja Asthana - 1 month ago 15
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>();
stringList.add("123");
stringList.add("456");
stringList.add("789");


and BigDecimal List as

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


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

Any help is appreciated. Thanks.

Answer

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?