Reputation: 49
I have a reactive program and i am adding to an Arraylist employees, as long as there isn't an employee with the same id following the code bellow.The thing is that it returns null even though the Arraylist has no employees in, So there can't be one with the same.
public Uni<Employee> addEmployeee(Employee employee){
return Multi.createFrom().iterable(employees)
.onItem().transform(empl -> {
if(empl.getId().equals(employee.getId())){
return null;
}else {
employees.add(employee) ;
}
return employee ;
}).toUni() ;
}
I have achieved that with the following code but i think the previous code is better.
public Uni<Employee> addEmployee(Employee employeeToAdd){
return Uni.createFrom().item(employees)
.onItem().transform(employees ->{
Optional<Employee> exists = employees.stream().filter(empl -> empl.getId().equals(employeeToAdd.getId())).findFirst();
if(exists.isEmpty()){
employees.add(employeeToAdd);
return employeeToAdd;
}
return null;
});
}
Can someone tell me what i'm doing wrong here ?
Upvotes: 0
Views: 1263
Reputation: 8206
The code with Multi
should be:
public Uni<Employee> addEmployeee(Employee employee){
return Multi.createFrom()
.iterable( employees )
.filter( entry -> entry.getId().equals( employee.getId() ) )
.collect()
.first()
.map( found -> {
if ( found == null ) {
// Not in the list
employees.add( employee );
return employee;
}
// Already in the list
return null;
} );
}
The original solution doesn't work because you are applying the same code for each entry of the employees
collection
But I don't know if I would use a Multi in this case, it seems like you can rewrite the code as:
private boolean contains(Employee employee) {
for (Employee e : employees) {
if ( e.getId().equals( employee.getId() ) {
return true;
}
}
return false;
}
public Uni<Employee> addEmployee(Employee employeeToAdd){
if ( contains( employeeToAdd ) ) {
return Uni.createFrom().nullItem();
}
employess.add(employeeToAdd);
return Uni.createFrom().item(employeeToAdd);
}
That looks simpler.
Also, if Employee
implements Comparable
, you can just use employees.contains(employeeToAdd)
.
Upvotes: 1