Reputation: 11639
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>();
Upvotes: 3
Views: 2777
Reputation: 121702
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.
Upvotes: 6
Reputation: 13738
Assuming you actually want your ArrayList
to contain Double
s 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>
.
Upvotes: 2