lundi 6 septembre 2021

How to get the item from the list based multiple conditions in java?

How to get the item from the list based multiple conditions in java?

List<Employee> employees = List.of(new Employee(1, 'AA'), new Employee(2, 'BB'), new Employee(3, 'CC'), new Employee(4, 'DD'));

I need to get the employee based on name,

Employee emp = null;

for (Employee e : employees) {
   if (e.getName.equals('AA')) {
      emp = e;
   }
}

if (emp == null) {
   for (Employee e : employees) {
     if (e.getName.equals('BB')) {
        emp = e;
     }
  }
}

if (emp == null) {
   for (Employee e : employees) {
      if (e.getName.equals('DD')) {
        emp = e;
     }
   }
 }

How to simplify the above code in java?

Aucun commentaire:

Enregistrer un commentaire