3

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>();
2
  • If you use Guava, yes. The JDK per se has no such mechanism, at least not up to version 7. Version 8 will have support for it, though. Commented Jun 1, 2013 at 15:30
  • Side note: what's the point of assigning an empty ArrayList to S (which should be named s), if you reassign a new list (returned by FillTheList(), which should be named fillTheList()) to S immediately after? Commented Jun 1, 2013 at 15:34

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just for the record, in Java 8, you can do List<Double> d = s.stream().map(Double::valueOf).collect(Collectors.toList());
2

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>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.