I am working on a Spring Boot application and I am not so confidend with the new Java 8 features. I have the following problem.
In my code I have this service method:
@Override
public List<User> getClientsOfASubAgentUser(int subAgentId) throws NotFoundException {
Optional<User> retrievedUser = this.userRepository.findById(subAgentId);
if(retrievedUser.isEmpty()) {
throw new NotFoundException(String.format("The SUB-AGENT user having ID or email %s was not found", Integer.toString(subAgentId)));
}
// CHECK IF THE Set<UserType> returned by the getUserTypes() method contain an object having "typeName" field value equals to "SUB-AGENT"
if(retrievedUser.get().getUserTypes().????)
List<User> clientsList = this.userRepository.findByParent_Id(subAgentId);
return clientsList;
}
My problem is on this line (that is incomplete):
// CHECK IF THE Set<UserType> returned by the getUserTypes() method contain an object having "typeName" field value equals to "SUB-AGENT"
if(retrievedUser.get().getUserTypes().????)
The getUserTypes() return a Set . This is the UserType entity class:
@Entity
@Table(name = "user_type")
@Getter
@Setter
public class UserType implements Serializable {
private static final long serialVersionUID = 6904959949570501298L;
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "type_name")
private String typeName;
@Column(name = "description")
private String description;
@ManyToMany(cascade = { CascadeType.MERGE })
@JoinTable(
name = "user_type_operation",
joinColumns = { @JoinColumn(name = "fk_user_type_id") },
inverseJoinColumns = { @JoinColumn(name = "fk_operation_id") }
)
Set<Operation> operations;
public UserType() {
super();
// TODO Auto-generated constructor stub
}
public UserType(String typeName, String description) {
super();
this.typeName = typeName;
this.description = description;
}
}
Basicallu I need to find a smart way (maybe using lambda function?) to check if into the Set returned by the getUserTypes() there is a UserType object having the typeName field equals to the SUB-AGENT string.
How can I correctly and nicely implement this behavior?
You can use anyMatch
for this. It is a terminal operation on the stream which returns true if the passed predicate (condition) evaluates to true for at least one element (UserType instance). It is a short-circuiting operation.
boolean hasTypeName = retrievedUser.get().getUserTypes()
.stream()
.anyMatch(userType -> userType.getTypeName.equals("SUB-AGENT")
if (hasTypeName) {...}
or inline it as
if (retrievedUser.get().getUserTypes()
.stream()
.anyMatch(userType -> userType.getTypeName.equals("SUB-AGENT")) {...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.