How to convert Collection <Number> to collection <Integer> security?

I have Collection<Number>, but I needCollection<Integer>

How can I convert it to security?

And the more common problem:

How to convert Collection<Parent>toCollection<Child>

+4
source share
5 answers

Guava example :

import com.google.common.base.Function;
import com.google.common.collect.Collections2;

Collection<Number> collection = ...
return Collections2.transform(collection, new Function<Number, Integer>() {
  @Nullable
  @Override
  public Integer apply(@Nullable Number input) {
    if(input == null) {
      return null;
    }
    return input.intValue();
  }
});

Note. Guava is an external library, you will need to import it.

+2
source

You can try this

    Collection<Number> numbers = ...
    Collection<Integer> integers = numbers.getClass().newInstance();
    for(Number n : numbers) {
        integers.add(n == null ? null : n.intValue());
    }
+3
source

-

public static Collection<Integer> convert(Collection<Number> in) {
  List<Integer> al = new ArrayList<Integer>();
  for (Number n : in) {
    if (n != null) {
      al.add(n.intValue());
    }
  }
  return al;
}
+2

instanceof.

Iterator<Number> itr = collection.iterator();
 while(itr.hasNext()) 
 {
       Number number = itr.next();
       if(number instanceof Integer)
       {
             Integer value = (Integer)number ;
             System.out.print("Integer is "+value );
       }

  }
+1

For each cycle, to iterate through a collection that has any type of numeric data, and then individually insert the conversion of these numeric data types into an integer one into another set.

List<Integer> i =  new ArrayList<Integer>();
for (Number n : in){
i.add(n.intValue()); 
}}
0
source

All Articles