Dan
Dan

Reputation: 37

java initialize multiple Strings from a String array

I am getting a String array back from a service (or actually a comma separated String which I'm splitting into a String array), and I want to extract those into separate Strings with meaningful names, e.g.:

String value = contents[0];
String name = contents[1];
String date = contents[2];
String status = contents[3];
...

Since the array is long and there are many such Strings to extract, I'm looking for the shortest way to do this, but couldn't find anything on SO/ the web. Thanks!

Edit

As an example, the input could be something like ["foo","bar","2017/04/01","A"], I want to extract those to meaningfully named Strings as described above, and then use those along the way, e.g. call function1(name, date) and then function2(name, value) etc. - I only want this translation (which needs to know which array index holds what data) to happen once and spare my code the need to know this mapping of array index to meaning everywhere. So I could have a translate function that does that and inserts the values into a map or something, but I thought that since these are all Strings there should be a way for me to initialize all of them at once.

Upvotes: 0

Views: 1939

Answers (2)

JayK
JayK

Reputation: 3141

Unless the input data contains field names or other metadata you will not get around a piece of code that associates names with indices, like in your code snippet above.

You could create a class for the kind of object encoded in the string array and supply a constructor or static factory method that initializes the object from a string array.

class WhateverItIs
{
   public static WhateverItIs fromStrings(String[] strings)
   {
       WhateverItIs instance = new WhateverItIs();
       instance.value = strings[0];
       instance.name = strings[1];
       // ...
       return instance;
   }

   private String value;
   private String name;
   // add getters
}

Clients can then access the properties of the created object.

Regarding the edit of your question: the functions you mentioned could then become methods of the class, possibly not needing any parameters any more because the data is in the instance variables.

Upvotes: 1

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

Why do you want to use have multiple Strings from the array. It will unnecssarily increase the JVM memory. A better option is to have it in a list. having said that if the data is in the form of name and value, you can always use a map, where key could be the name and value as is.

Upvotes: 0

Related Questions