Home > Back-end >  How to update Object Array Dynamically in java
How to update Object Array Dynamically in java

Time:04-10

I have a list of object say List<Employee> and Employee class has id,name,age as property. just want to convert list into Object[].

i tried

Object[] arr = employeeList.toArray();

but in my object array i get 3 different employee object. i want output like

Object arr = {employee1id,employee1name,eployee1age,employee2id,employee2name....} and so on.

please help.

CodePudding user response:

If an employee record has its mapping as Java POJO class, just try sth like this: Arrays.stream(arr).map(o -> (Employee) o).flatMap(o -> Arrays.stream(new Object[]{o.id, o.name, o.age})).collect(Collectors.toList()). You have List<Object> as a result, which you can convert to array like this

I assume, that Object arr = {employee1id,...} is misspelling, and you'd like to have Object[] arr = {employee1id,...}

CodePudding user response:

Can you try having a method inside the Employee class that adds the properties to an array? you can then run through a loop to pass a list , such that it collects all the properties of your looping employees.

public class MyClass {
    public static void main(String args[]) {
      Employee emp1 = new Employee();
      emp1.id = "1";
      emp1.name = "John";
      
      Employee emp2 = new Employee();
      emp2.id = "2";
      emp2.name = "Doe";
      
      List<Employee> empList = new ArrayList<Employee>();
      empList.add(emp1);
      empList.add(emp2);
      
      List<String> resultList = new ArrayList<String>();
      for(Employee employee: empList) employee.addToArray(resultList);
      
      Object[] resultArray = resultList.toArray();
      System.out.println(Arrays.toString(resultArray));
      
    }
}



 public class Employee{
    public String id;
    public String name;
    
    public void addToArray(List a){
        a.add(this.id);
        a.add(this.name);
    }
}
  •  Tags:  
  • java
  • Related