Converting Treeset (object []) into an int[] array?

I am making a method to sort using Hashset/Treeset, however I am stopped when it comes to taking my Treeset and trying to return it back from the method. I know I could change the return type to Object[], but I was wondering if there was any way to keep the return type as an int[].

static int[] sortArrayWithHashset(int array[]) {
    HashSet<Integer> myHashSet = new HashSet<Integer>();
    for (int i = 0; i > array.length;i++) {
        myHashSet.add(array[i]);
    }

    TreeSet<Integer> myTreeSet = new TreeSet<Integer>();
    myTreeSet.addAll(myHashSet);
    //array = myTreeSet.toArray();
    return array;
}

To convert a collection into an array you can either use Stream IPA or create an array manually and populate it inside a loop.

public static int[] collectionToIntArray(Collection<Integer> source) {
        return source.stream()
                .mapToInt(Integer::intValue)
                .toArray();
    }
public static int[] collectionToIntArray(Collection<Integer> source) {
        int[] result = new int[source.size()];
        int pos = 0;
        for (int next: source) {
            result[pos++] = next;
        }
        return result;
    }

The code you've provided is slightly contrived. There are things you need to be aware of:

  • Set will discard all duplicates from the source array;
  • you can add array elements into a TreeSet directly;
  • write your code against interfaces not against class, that provides more flexibility, like that
    Set<Integer> myHashSet = new HashSet<>();
    NavigableSet<Integer> myTreeSet = new TreeSet<>();
  • Lastly, I guess you were practicing in order to get familiar with the Set interface implementations and hence didn't aim for this code to be efficient. To complete to overall picture it is worth reminding that to sort an array you can simply use Arrays.sort().