java123999
java123999

Reputation: 7394

Creating objects dynamically using a list of Strings?

I am trying to create objects by using a list of Strings that will populate their fields. For example I have the list of strings, Note that the values repeat after every 3. i.e. id, name , address.

List<String> myList = "Id1", "name1", "address1", "Id2", "name2", "address2";

I would like to dynamically create a number of Person Objects (shown below) using this list

Person object:

public class Person {

    private String id;
    private String name;
    private String address;

     public Person() {
    }

    public Person(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    //standard getters and setters

}

What I want to do is have a method that will take the list of strings as an input and then create the objects dynamically. How could I best do this?

I know that I could do the following if I knew that I was definitely populating 2 objects, but the problem is that there may be more or less.

public List<Person> createObjectsFromStringList(List<String> list){

    List<person> personList = new Arraylist<>();

    Person person1 = new Person(list.get(0), list.get(1), list.get(2));
    Person person2 = new Person(list.get(3), list.get(4), list.get(5));

    personList.add(person1);
    personList.add(person2);

    return personList;

}

Upvotes: 0

Views: 1076

Answers (4)

Zircon
Zircon

Reputation: 4707

A simple for loop can do the work:

public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    //We use < size-2 here because we access 2 indeces ahead of x in this loop
    for(int x=0; x<list.size()-2; x+=3) { 
        personList.add(new Person(list.get(x), list.get(x+1), list.get(x+2));
    }
    return personList;
}

At first glance, I feel like having the different field values across one List is a sign of a poor code structure, but maybe you're already stuck with this List as-is.

Edit:

Now let's suppose you want a partial Person based on the number of remaining elements. Supposing they are still in the same order, you could modify this method to check the validity of the current index for each field:

public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    int size = list.size();
    //Now we remove the "-2" from size check because we will handle this ourselves
    for(int x=0; x<size; x+=3) {
        String id = list.get(x); //Obviously valid
        String name = x+1 < size? list.get(x+1) : null;
        String address = x+2 < size? list.get(x+2) : null;
        personList.add(new Person(id, name, address);
    }
    return personList;
}

We're using the ternary operation ? ... : null here, so if we run out of elements we set the associated Person field to null instead of using an out-of-bounds index.

Upvotes: 2

Boris Zhguchev
Boris Zhguchev

Reputation: 314

If you use java 8 you can try something like this:

  public List<Person> createObjectsFromStringList(List<String> list) {
      //partition by 3 and list.size.
    Map<Integer,List<Integer>> map = IntStream
            .range(0,list.size())
            .boxed()
            .collect(Collectors.groupingBy(e->(e)/3));

    List<Person> personList = new ArrayList<>();

    map.entrySet().forEach(e->{
        List<String> per= e.getValue();
        Person p = new Person(per.get(0),per.get(1),per.get(2));
        personList.add(p);
    });
    return personList;
}

Upvotes: 0

Jay Smith
Jay Smith

Reputation: 2480

As you want to access your elements sequentially you should use java.util.LinkedList in such loop

    for(true)
        if(linkedList.size()>=3){
                 Person person=   new 
Person(linkedList.removeFirst(),linkedList.removeFirst(),linkedList.removeFirst());

                 personList.add(person);
    }
        else break;

But ArrayList and its get method is good for random access by index which is not your case

Upvotes: 0

gvlachakis
gvlachakis

Reputation: 474

You can use recursion

public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();    
for(int i=0; i<list.size(); i++){
     personList.add(new Person(list(i),list(i+1),list(i+2)));
     i+=2;
}
 return personList;
}

Notice that restructuring your list would me much better. make it like this:

List<String> myList = "Id1_name1_address1", "Id2_name2_address2";

Or even use different lists (it is much better). If you change your list structure as above then change the code to this :

public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();    
for(int i=0; i<list.size(); i++){
     String[] info= list(i).split("_"); // this will give u a 3element array of yout info IdX nameX addressX
     personList.add(new Person(info(0),info(1),info(2)));
     }


return personList;

Upvotes: 0

Related Questions