Is it possible to convert an Arraylist<Double> to Arraylist<Integer>?

Asked

Viewed 136 times

1

So, guys, I’d like to know if there is and how to make the conversion of a ArrayList<Double> in a ArrayList<Integer>?

  • 1

    You were quick in editing huh

  • Malz guys, I ended up putting wrong word in the title.

  • Just do it manually item by item.

  • It is possible but you will lose decimal accuracy of numbers

  • @Articuno, sure as I would then? Following the example of LINQ?

  • His answer is the solution. There is no way to maintain decimal accuracy in integer, this is the basic rule of mathematics

  • @Christiangomesdasilva I realized that you have no accepted question. Just to warn you, you can always accept an answer to your questions, just dial the V on the side of the answer you want to leave as correct =D

  • @LINQ thanks a lot for the tip, I still don’t understand very well how to use the stack in the correct way.

  • @Christiangomesdasilva Young man, has the answer met your needs? Do you need me to improve on it?

Show 4 more comments

1 answer

11

You need to do something so that all items from the original list return its integer value. This can be done with the method intValue().

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 on Repl.it.

In previous versions.

Note that the right-hand type inference of the generic declaration was only inserted in Java 7 - see documentation. Still, the answer is valid for all lower versions, just need to change the instantiation of Arraylist of new ArrayList<>() for new ArrayList<Integer>().

List<Double> doubles = /* lista original */;

List<Integer> integers = new ArrayList<>();

for(Double d : doubles) {
    integers.add(d.intValue());
}

See working on Repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.