简体   繁体   中英

How to convert arraylist in java?

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?

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.

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);

您可以将cast int键入为double:

(double)array.get(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM