Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic String Array if we dont know number of strings in the beginning?

Tags:

java

I have a HashMap<String, String>. If I want to create string array of hashmap.values(), we can create it as

String[] strArray = new String[hashmap.size()]

But my problem is if hashmap values contain "A,B,C" then I need to add A and B and C to strArray.

like image 563
Praveen Hiremath Avatar asked Jun 21 '12 12:06

Praveen Hiremath


People also ask

How do you initialize a string array in Java without size?

There are two ways to declare string array - declaration without size and declare with size. There are two ways to initialize string array - at the time of declaration, populating values after declaration. We can do different kind of processing on string array such as iteration, sorting, searching etc.


2 Answers

Use an ArrayList.

List<String> myList = new ArrayList<String>();

No matter what the size is of your HashMap you can easily work with your ArrayList.

If you need an array, you can use

String[] arr = myList.toArray(new String[myList.size()]);

when you have finished.

like image 187
Kazekage Gaara Avatar answered Oct 26 '22 19:10

Kazekage Gaara


You can take a copy of the values whenever you need an array.

Map<Double, String> map = ...
String[] values = map.values().toArray(new String[map.size()]);

If you change the map (even if the size doesn't change), the array won't change and you need to take another copy. Do the values need to be unique?

So i need to create the string Array with values (A,B,C,P,Q,R...,Z).

In that case it appears you want to do the following.

Map<Double, String> map = ...
List<String> valueList = new ArrayList<>();
for(String value: map.values())
   valueList.addAll(Arrays.asList(value.split(",")));
String[] values = valueList.toArray(new String[valueList.size()]);
like image 27
Peter Lawrey Avatar answered Oct 26 '22 19:10

Peter Lawrey