Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

can I easily make an array of objects with arrays of all parameter's and no for loops in java

I have arrays of Strings and Ints, each array contains one parameter for all objects. Is there a way to directly make an array of those objects without a for loop. For example

public class PersonHandler {
String[] name = {Bob, Joe, Jhon, Jane};
int[] age = {20, 23, 30, 22};
PersonMaker make = new PersonMaker(name, age);
}
public class PersonMaker {
Person[] people;
public PersonMaker(String[] name, int[] age) {
//this implementation is what I need help with, I want to fill array people with person objects
//initialized with the names and ages in the arrays
}
}
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

I tried a for loop but I want something simpler, especially for more parameters, google and searching here did not find what I was looking for.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Certainly! If you want to avoid using a for loop and you have arrays of the same length representing different parameters for objects, you can use the IntStream and Stream classes along with mapToObj to create an array of objects. Here’s how you can modify your PersonMaker class to achieve this:

import java.util.stream.IntStream;

public class PersonHandler {
    String[] names = {"Bob", "Joe", "John", "Jane"};
    int[] ages = {20, 23, 30, 22};
    PersonMaker make = new PersonMaker(names, ages);
}

public class PersonMaker {
    Person[] people;

    public PersonMaker(String[] names, int[] ages) {
        // Use IntStream.range to create indices and map each index to a Person object
        people = IntStream.range(0, names.length)
                .mapToObj(i -> new Person(names[i], ages[i]))
                .toArray(Person[]::new);
    }
}

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

In this example, IntStream.range is used to generate indices from 0 to names.length - 1, and then mapToObj is used to map each index to a Person object using the corresponding values from the names and ages arrays. The result is an array of Person objects assigned to the people field.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading