Get array of Map's keys

52,948

Solution 1

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();

Solution 2

Use primeKeys.toArray() instead of toArray(primeKeys).

Solution 3

toArray() is a member of the Collection class, so just put Collection.toArray(...) and import java.util.Collection;

Note: toArray() returns an Object[], so you'll have to cast it to Integer[] and assign it to an Integer[] reference:

Integer[] array = (Integer[])Collection.toArray( someCollection );

Thanks to autoboxing, Integers now work like ints, most of the time.

edit: dan04's solution is pretty cool, wish I'd thought of that...anyway, you'll still have to cast and assign to a Object[] type.

Share:
52,948
Rushy Panchal
Author by

Rushy Panchal

Updated on November 03, 2020

Comments

  • Rushy Panchal
    Rushy Panchal over 3 years

    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?

  • Rushy Panchal
    Rushy Panchal about 11 years
    int[] keys = primeKeys.toArray() highlights the parentheses and I get this error: incompatible types.
  • Stavro Xhardha
    Stavro Xhardha over 5 years
    saved my life , I would recommend just for(Integer element : keys) array[index++] = element.intValue(); to be replaced with for(Integer element : keys) array[index++] = element to remove boxing