0

I have created one hashmap. All I need to do is get the keys from the hashmap and store in a String[] array.
This is what I was doing but it's not correct.

 HashMap<String, String> columnHeaders = new HashMap<String, String>();
        columnHeaders.put("Id", "101");
        columnHeaders.put("First Name","AAA");
        columnHeaders.put("Last Name","BBB");
        columnHeaders.put("Country","CCC");
        columnHeaders.put("City","DDD");
        columnHeaders.put("State","EEE");
        columnHeaders.put("Province","FFF");
}

 String[] keyHeaders=null;
            for(Map.Entry<String, String> param : columnHeaders.entrySet()){
            String key = param.getKey();
            keyHeaders = key.split(";");
            Arrays.toString(keyHeaders);
   }

I kept the String[] global because I need pass it to a for loop.
Could please someone help me with this?

3
  • 2
    Why are you splitting the key if none has ;? If you can use the keys as they are, just use String[] keyHeaders = columnHeaders.keySet().toArray(new String[0]);. Commented Aug 3, 2021 at 14:21
  • 2
    You are overthinking this way to much. HashMap already has a method to return a Set of your keys, and Set has a method to convert itself to an array: String[] keys = columnHeaders.keySet().toArray(new String[0]); Commented Aug 3, 2021 at 14:21
  • So I don't need this for each loop to iterate through the map? Commented Aug 3, 2021 at 14:33

2 Answers 2

1

You can do it like this.

HashMap<String, String> columnHeaders =
        new HashMap<String, String>();
columnHeaders.put("Id", "101");
columnHeaders.put("First Name", "AAA");
columnHeaders.put("Last Name", "BBB");
columnHeaders.put("Country", "CCC");
columnHeaders.put("City", "DDD");
columnHeaders.put("State", "EEE");
columnHeaders.put("Province", "FFF");

String[] keys = columnHeaders.keySet().toArray(String[]::new);

for (String k : keys) {
    System.out.println(k);
}

Prints

State
First Name
Country
Id
City
Last Name
Province

   
Sign up to request clarification or add additional context in comments.

2 Comments

what do we mean by String[]::new inside toArray. would you please tell what does it have wrong String[] keys = columnHeaders.keySet().toArray()
Since the stream is of an Object, toArray would return an array of object (e.g. Object[]); But to change to a specific Object[] type you need to tell it which type. I could also have done String[] keys = columnHeaders.keySet().toArray(new String[0]). See the Collection Interface for more detail.
0

Try change 101 to "101" or String.value (101)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.