Is it possible to convert an ArrayListDouble to ArrayListInteger?

1

So, guys, I wonder if there is and how to convert a ArrayList<Double> to a ArrayList<Integer> ?

    
asked by anonymous 10.11.2017 / 19:37

1 answer

11

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

See working in Replit.

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

See working in Replit.

    
10.11.2017 / 19:40