Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Collection<Number> to Collection<Integer> safety?

I have Collection<Number> but I needed Collection<Integer>

How can I convert it safety?

And more common issue:

How to convert Collection<Parent> to Collection<Child>

like image 877
gstackoverflow Avatar asked Feb 14 '23 07:02

gstackoverflow


1 Answers

You can try this

    Collection<Number> numbers = ...
    Collection<Integer> integers = numbers.getClass().newInstance();
    for(Number n : numbers) {
        integers.add(n == null ? null : n.intValue());
    }
like image 112
Evgeniy Dorofeev Avatar answered Mar 06 '23 09:03

Evgeniy Dorofeev