Mark Mikofski
Mark Mikofski

Reputation: 20198

concatenate fields from array of Java objects

I am a newbie to Java. I have an array of objects that have a string field. I can concatenate all of the strings into an string array by looping, but it's very inelegant.

int numObj = obj.length;
String[] strArray = new String[numObj];
for (int i = 0; i < numObj; i++) {
    strArray[i] = obj[i].strField;
}

Is there a way to concatenate that single field from all of the objects into a string array in one command? e.g.:

String[] strArray = (String[]){obj[].strField};

This doesn't work because obj[] is an array and so it doesn't have any fields, but using {obj.strField} doesn't work either, because there is no object called obj. BTW I really don't have to recast the field or do .toString() because it is already a string.

I looked at many, many of the other posts (but perhaps not enough?) related to this but I still could not figure this out. There are some that refer to converting an object array to a string array, but I don't think those posts mean converting a particular field in the objects, but the object itself, as an uncast type.

In MATLAB this would be trivial: strCellArray = {obj.strField}; would create a cell array of strings from all of the strFields in obj instantly.

Thanks for your help.

Upvotes: 1

Views: 1871

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

What you did is the only way. You don't have to create a variable for the length of the array, though. And using public fields is, 99.99% of the times, a very bad idea:

String[] strings = new String[objects.length];
for (int i = 0; i < objects.length; i++) {
    strings[i] = objects[i].getStringField();
}

Upvotes: 7

Related Questions