Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using keySet() method then changing the Set to a String Array? Java

So this should be really simple since I know it's possible (I just don't understand 'Set' very much).

So basically there is this TreeMap, let's call it aTree. So I need to do something like:

somethingHereProbably = aTree.keySet();
somethingHereProbably.toStringArray();
like image 363
askaka12 Avatar asked Dec 31 '12 00:12

askaka12


People also ask

How do you change a set to an array in Java?

Create a Set object. Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.

What is keySet method in Java?

HashMap keySet() Method in Java keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Syntax: hash_map.keySet()


1 Answers

You can do

Map<String, Object> map = ...
String[] strings = map.keySet().toArray(new String[map.size()]);

This works for any kind of map, including TreeMap

like image 198
Peter Lawrey Avatar answered Oct 21 '22 09:10

Peter Lawrey