0

Is it possible to convert integer arraylist in java to double arraylist. For example, I have;

ArrayList<Integer> array  = new ArrayList<Integer>();

one example of how I am using it, is;

System.out.println(array.get(2));

but in the process of printing this out, I want to covert it into double, is it possible?

1
  • If all you're doing is accessing the members of the array, and not changing it, you can just cast when you access: println((double)array.get(2)); Commented Feb 22, 2015 at 13:35

3 Answers 3

3

In Java 8, you can simply:

double[] arr = yourList.stream().mapToDouble(i -> i).toArray();
// now you can new ArrayList<Double>(Arrays.asList(arr))

If you work with earlier versions of Java, you can iterate on the arraylist and construct new one manually.

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

5 Comments

I am using java 1.6/7
I don't have access to java 8 at my place
@Henry You can manually iterate on it, convert each value and insert to the new Double arraylist.
I am updating my system, I will probably have it in another couple of months :) hopefully. ATM, I have to stick with 1.6/7
"// now you can new ArrayList<Double>(Arrays.asList(arr))" Well no it'll give you a List<double[]>. But you don't need mapToDouble; if you want a List at the end, List<Double> list = yourList.stream().map(Double::valueOf).collect(Collectors.toList()); will do the job.
1

If you must use Java 6/7 a simple for-loop will do the trick:

List<Integer> ints = Arrays.asList(1, 2, 3, 4);
List<Double> doubles = new ArrayList<Double>(ints.size());

for (Integer i : ints) {
    doubles.add(Double.valueOf(i));
}

Or, if you simply wish to print it just assign it or cast it to a double:

double d = ints.get(0);

Comments

-1

You can type cast int to double :

(double)array.get(2)

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.