So, guys, I wonder if there is and how to convert a ArrayList<Double>
to a ArrayList<Integer>
?
So, guys, I wonder if there is and how to convert a ArrayList<Double>
to a ArrayList<Integer>
?
You need to do something so all items from the original list will return their entire value. This can be done using the intValue()
method.
Note that obviously the decimal part of the numbers will be lost.
Using Java 8
List<Double> doubles = /* lista original */;
List<Integer> integers = doubles.stream()
.map(d -> d.intValue())
.collect(Collectors.toList());
In earlier versions.
Note that the type inference on the right side of the generic declaration was only inserted in Java 7 - see documentation . However, the answer is valid for all lower versions, you just need to switch the ArrayList instantiation from new ArrayList<>()
to new ArrayList<Integer>()
.
List<Double> doubles = /* lista original */;
List<Integer> integers = new ArrayList<>();
for(Double d : doubles) {
integers.add(d.intValue());
}