How to create a dynamic array of strings if we do not know the number of rows in the beginning?

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

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

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

+5
source share
3 answers

Use ArrayList.

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

Regardless of your size HashMap, you can easily work with ArrayList.

If you need an array, you can use

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

when you are done.

+21
source

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()]);

( ), , . ?

, Array (A, B, C, P, Q, R..., Z).

.

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()]);
+2

Do I need to be an array? Using Maps, you can get a key for a set of values.

0
source

All Articles