9

I want to display a graph and for displaying that i need integer values.I get this from my code

    Collection c = Sort.values();

Is there any way that i convert collection in such a way that i get integer values?i get this when i print the collection c

    [64770, 26529, 13028, 848, 752, 496]
Xara
  • 8,748
  • 16
  • 52
  • 82

4 Answers4

15

Assuming the values are of type Integer, you can try this:

Collection c = Sort.values();
Integer[] a = (Integer[])(c.toArray(new Integer[c.size()]));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • For efficiency purposes, can this answer be changed to get a `int[]` instead of `Integer[]`? And was this for an older version of Java before autoboxing? – SimonT Apr 30 '14 at 11:41
  • @SimonT "can we use `int[]`?" No, not in Java. "was this for Java before autoboxing?" There's no autoboxing in this code (it's not necessary here). Collection could be made generic, but that is not necessary either. – Sergey Kalinichenko Apr 30 '14 at 14:05
3
for (Integer value : c) {
    int i = value.intValue();
    //do something with either value or i
}
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
2

The question was: conversion to int array
Integer[] can not be assigned to int[] or vice versa

int[] array = c.stream().mapToInt( i -> i ).toArray();
Kaplan
  • 2,572
  • 13
  • 14
1

Simply:

Integer[] yourArrayVar = yourCollectionVar.toArray(new Integer[0]);

java just needs to know what kind of array to produce.

Amr Lotfy
  • 2,937
  • 5
  • 36
  • 56