Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of Map's keys [duplicate]

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?

like image 746
Rushy Panchal Avatar asked Apr 24 '13 23:04

Rushy Panchal


People also ask

Can Hashmaps have duplicates?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Can LinkedHashMap have duplicate keys?

A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.

Does TreeMap allow duplicate keys?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.

Does HashSet allow duplicate keys?

In HashSet, we store objects. It does not allow duplicate keys, but duplicate values are allowed. It does not allow duplicate values. It can contain a single null key and multiple null values.


3 Answers

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();
like image 178
Eng.Fouad Avatar answered Oct 10 '22 01:10

Eng.Fouad


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

like image 37
dan04 Avatar answered Oct 10 '22 01:10

dan04


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.

like image 2
Ray Stojonic Avatar answered Oct 09 '22 23:10

Ray Stojonic