0

I have a String array contains name, age, and gender of 10 customers. I tried to convert it to Customer array. I tried to copy each elements of String array into Customer array but it's not compatible. How do I insert elements from String array into Customer array?

//String[] customerData is given but too long to copy
Customer[] custs = new Customer[numberOfCustomer];
for (int x = 0; x < customerData.length; x++) {
    custs[x] = customerData[x];
}
0

4 Answers 4

1

Assuming that Customer class has an all-args constructor Customer(String name, int age, String gender) and the input array contains all the fields like:

String[] data = {
    "Name1", "25", "Male",
    "Name2", "33", "Female",
// ...
};

The array of customers may be created and populated like this:

Customer[] customers = new Customer[data.length / 3];
for (int i = 0, j = 0; i < customers.length && j < data.length; i++, j += 3) {
    customers[i] = new Customer(data[j], Integer.parseInt(data[j + 1]), data[j + 2]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Create a temporary customer object inside the loop and populate it with the data. Then assign custs[x] to the temporary object.

Comments

0

If you have a 2d array of strings and an all-args constructor in the Customer class, then you can convert an array of strings to an array of objects like this:

static class Customer {
    String name, age, gender;

    public Customer(String name, String age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return name + " " + age + " " + gender;
    }
}
public static void main(String[] args) {
    String[][] arrStr = {
            {"John1", "22", "Male"},
            {"John2", "21", "Male"},
            {"John3", "23", "Male"},
            {"John4", "24", "Male"},
            {"John5", "20", "Male"}};

    Customer[] customers = Arrays.stream(arrStr)
            // convert an array of strings to an array of objects
            .map(arr -> new Customer(arr[0], arr[1], arr[2]))
            .toArray(Customer[]::new);

    // output
    Arrays.stream(customers).forEach(System.out::println);
}

Output:

John1 22 Male
John2 21 Male
John3 23 Male
John4 24 Male
John5 20 Male

Comments

0

You have json string , use objectMapper to convert json string to object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.