Rathishkumar
Rathishkumar

Reputation: 119

ArrayList to user defined class array

I have a List<User> userList need to convert to UserData[]

for(int i = 0; i < userList.size(); i++){
    userData[i] = userList.get(i);
}

It always returns null though the list size is 1. can anyone help on this.

Upvotes: 3

Views: 687

Answers (3)

just another option, this time using the power of java8 streams:

List<Foo> myList = Arrays.asList(new Foo(), new Foo(), new Foo(), new Foo());
Foo[] stringArray = myList.stream().toArray(Foo[]::new);

Edit:

Stream is actually not necessary so you can still do:

Foo[] fooArray = myList.toArray(new Foo[0])

Upvotes: 3

Jangachary
Jangachary

Reputation: 138

Here is the code try this

import java.util.ArrayList;

public class ArrayListTest {

static UserData[] userdata = new UserData[3];

public static void main(String[] args) {
    ArrayListTest alt = new ArrayListTest();
    ArrayList<UserData> users = alt.arrayTest();

    for (int i = 0; i < users.size(); i++) {
        userdata[i] = users.get(i);
    }

    for (UserData ud : userdata) {
        System.out.println("User Name " + ud.getName());

    }

}

private ArrayList<UserData> arrayTest() {
    ArrayList<UserData> userList = new ArrayList<>();
    userList.add(new UserData("user 1"));
    userList.add(new UserData("user 2"));
    userList.add(new UserData("user 3"));
    return userList;
}

private class UserData {

    private final String name;

    public UserData(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

}

this is the output screen

Upvotes: 0

Ted Cassirer
Ted Cassirer

Reputation: 364

Collections can be converted to arrays:

UserData[] userArray = userList.toArray(new UserData[userList.size()])

Upvotes: 3

Related Questions