converting hashmap to stringarray

10,406

Solution 1

drinkar.keySet().toArray() returns Object[] not String[]

One of the way may be:

user Collections.toArray(StringArry)

(or)

Iterate through the keySet and add each element to array.

Solution 2

Use toArray(T[]) as:

String[] list = drinkar.keySet().toArray(new String[0]);

By giving an empty array as the argument, you tell toArray to create a new array of the same type for you that will be just of the correct size.


Just a note: If you can choose, it's usually more convenient (and safer) to work with collections such as ArrayList instead of arrays.

Solution 3

String st[]=hm.keySet().toArray(new String[hm.size()]);

Share:
10,406
DrWooolie
Author by

DrWooolie

Updated on August 09, 2022

Comments

  • DrWooolie
    DrWooolie over 1 year

    I am trying to convert a hashmap into an array, that I can put in a created string array. I however get java.lang. I have typeconverted my drinkar.keySet().toArray() to String[], but it will still not work.

    public String[] receiveArrayList(){
    
    String[] list = new String[0];
    
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            drinkar = (HashMap<String, ArrayList<String>>) (ois.readObject());
            System.out.println(drinkar);
    
            System.out.println(Arrays.toString(drinkar.keySet().toArray()));
            list = (String[]) (drinkar.keySet().toArray());
    
            for(int i = 0; i < list.length; i++){
                System.out.println(list);
            }
    
    
        } catch (ClassNotFoundException ex) {
            System.out.println(ex);
        } catch (IOException ex) {
            System.out.println(ex);
        }
        return list;
    
    }
    
  • DrWooolie
    DrWooolie over 11 years
    thanks, but i cant seem to get it right. i dont think i know how to iterate correctly.
  • kosa
    kosa over 11 years
    while(it.hasNext()){ String temp = it.next(); //then add temp to String array. }
  • DrWooolie
    DrWooolie over 11 years
    is there a way to add strings to arrays? doesnt seem like it
  • kosa
    kosa over 11 years
    arr[0]=temp; this will add temp at index 0
  • DrWooolie
    DrWooolie over 11 years
    it didnt work, i still get nothing. but i tried another way. created an arraylist, added temp to the arraylist and it worked and i could print it easily. but when i tried to convert it to array, it gave me java.lang.