Convert List<String> to new Object[]{}

I have this:

data.put(1, 
            new Object[] { listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName(),
            listUserColumns.get(field++).getName(), listUserColumns.get(field++).getName() });

And i want to cast this listUserColums (List of type String) directly to new Object[]( of type java.lang.object) but don`t know how?

Upvotes: 2

Views: 131

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533462

It appears that what you want is more like

data.put(1, listUserColumns.stream().map(c -> c.getName()).toArray());

for a sub set

data.put(1, listUserColumns.subList(from, to)
                           .stream().map(c -> c.getName()).toArray());

Upvotes: 1

Nikolay K
Nikolay K

Reputation: 3850

It depends on what you are intended to obtain and it is not clear from the question.

When you need to get array of names for all elements in your list, you can use Stream<T>

Object[] names = listUserColumns.stream().map(c -> c.getName()).toArray();

However, there is no way to cast this listUserColums, since array is the inner representation of ArrayList. You can create a new array that contains references to the same elements as the list with this

Object[] elements = listUserColumns.toArray();

In your case it looks like listUserColumns is not List<String>, that's why the results of these methods would be different (In the first case array of string, and in the second case array of your custom types).

Upvotes: 1

GBlodgett
GBlodgett

Reputation: 12819

You can do the toArray() method:

ArrayList<String> arr = new ArrayList<>();
arr.toArray()

Which:

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Upvotes: 0

Related Questions