Tuesday, September 20, 2022

[FIXED] How to print multiple Employee details with below requirement which collection type can be used in java?

Issue

I want to store data as below format to any function of java collection and print the output:-

[
   { id->100, name->'praveen', mobile-9455104973 },
   { id->101, name->'Saurbh', mobile-7355078643 },
   { id->103, name->'Shivendr', mobile-123456789 } 
]

Output:

ID   Name       Mobile
100  Praveen    9455104973
101  Saurbh     735078643
102  Shivendra  123456789

Solution

I recommend that you create an employee class.

public class Employee {
private int id;
private String name;
private long phoneNumber;

/**
 * @param id
 * @param name
 * @param phoneNumber
 */
public Employee(int id, String name, long phoneNumber) {
    super();
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
}

@Override
public String toString() {
    return id + "\t" + name + "\t" + phoneNumber + "\n";
}
}

After that you create a list of employees and initialize it with the employees you are interested in and print it.

List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(100, "praveen", 9455104973L));
    employees.add(new Employee(101, "Saurbh", 7355078643L));
    employees.add(new Employee(103, "Shivendr", 123456789L));
    
    System.out.println("ID\tName\tMobile");
    
    for (Employee e: employees)
        System.out.println(e.toString());

OUTPUT:

ID  Name    Mobile
100 praveen 9455104973

101 Saurbh  7355078643

103 Shivendr    123456789


Answered By - Fede Cana
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.