Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 454
Raja Asthana Avatar asked Dec 01 '22 22:12

Raja Asthana


2 Answers

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?

like image 173
Jon Skeet Avatar answered Dec 04 '22 10:12

Jon Skeet


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.

like image 41
Makoto Avatar answered Dec 04 '22 11:12

Makoto