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.
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?
At some level - either in an external library, a lower level library, or in your code - you'll have to iterate over the structure and create new BigDecimal
objects in your other list.
Now that Java 8 is effectively out, it can be expressed rather tersely as thus. This code assumes that you already have stringList
defined somewhere.
List<BigDecimal> bigDecimalList = stringList.stream()
.map(BigDecimal::new)
.collect(Collectors.toList());
This takes all of the contents of the stringList
, maps them across to the constructor of BigDecimal
, and collects them into a new List
object, which we then assign.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With