Get array of Map's keys
Question: I am trying to learn Java with a Python basis, so please bear with me.

I am implementing a Sieve of Eratosthenes method (I have one in Python; trying
to convert it to Java):

    
    
    def prevPrimes(n):
        """Generates a list of primes up to 'n'"""
        primes_dict = {i : True for i in range(3, n + 1, 2)}
        for i in primes_dict:
            if primes_dict[i]:
                num = i
            while (num * i <= n):
                primes_dict[num*i] = False
                num += 2
        primes_dict[2] = True
        return [num for num in primes_dict if primes_dict[num]]
    

This is my attempt to convert it to Java:

    
    
    import java.util.*;
    public class Sieve {
        public static void sieve(int n){
            System.out.println(n);
            Map primes = new HashMap();
            for(int x = 0; x < n+1; x++){
                primes.put(x, true);
            }
            Set primeKeys = primes.keySet();
            int[] keys = toArray(primeKeys);  // attempt to convert the set to an array
            System.out.println(primesKeys); // the conversion does not work
            for(int x: keys){
                System.out.println(x);
            }
            // still have more to add
            System.out.println(primes);
        }
    }
    

The error I get is that it cannot find the method `toArray(java.util.Set)`.
How can I fix this?


Answer: First of all, use generics:

    
    
    Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
    Set<Integer> keys = map.keySet();
    

Second, to convert the set to an array, you can use `toArray(T[] a)`:

    
    
    Integer[] array = keys.toArray(new Integer[keys.size()]);
    

and if you want `int` instead of `Integer`, then iterate over each element:

    
    
    int[] array = new int[keys.size()];
    int index = 0;
    for(Integer element : keys) array[index++] = element.intValue();
    

