I have a String arraylist and i am going to convert it to a double arraylist. Is there any way except using loops like for,While to convert it?
ArrayList<String> S=new ArrayList<String>();
S=FillTheList();
ArrayList<Double> D=new ArrayList<Double>();
In the JDK proper, up to version 7, no. JDK 8 will have functional programming support, though (see comment by @JBNizet below for the syntax).
You can use Guava to achieve this however:
final Function<String, Double> fn = new Function<String, Double>()
{
@Override
public Double apply(final String input)
{
return Double.parseDouble(input);
}
};
// with S the original ArrayList<String>
final List<Double> D = Lists.transform(S, fn);
Note that while there is no loop in this code, internally the code will use loops anyway.
More to the point of your original question however, you cannot cast a String to a Double, since these are two different classes. You have to go through a parsing method like shown above.
Assuming you actually want your ArrayList to contain Doubles when you're done, no, there's no alternative, you're going to have to loop through, converting each String to a Double and adding the Double to the new ArrayList.
Note that at runtime, Java doesn't actually know the type that a List contains - it doesn't know that it's an ArrayList<Double>, it just knows that it's an ArrayList. There's therefore no way for the JVM to know what operation needs to happen to convert the contents of your ArrayList<String> (which it also sees as ArrayList) and add them to your ArrayList<Double>.
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