Issue
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.
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.
Answered By - justinbitter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.