Reputation: 2074
I have an entity Issue
as following :
public class Issue{
private IssueElementEnum issueElement;
private IssueTypeEnum issueType;
private String title;
}
And I have a list of Issue
which I get from DAO:
List<Issue> issues = issueDAO.findAll();
In this list I have some Issue
object where issue.getIssueElement() == IssueElementEnum.USER
, I want to update these object by changing there title
field, for that I have to filter the list of issues
and create a list of type String from the result list, then I have to pass this list to a service that will return a list of new titles which will be used to replace the old titles.
This is what I tried :
List<Issue> issues = issueDAO.findAll();
List<Issue> userIssues = issues.stream().filter(a -> a.getIssueElement() == IssueElementEnum.USER).collect(Collectors.toList());
List<String> oldTitles = userIssues.stream().map(a -> a.getTitle()).collect(Collectors.toList());
List<User> users = userSVC.findByTitles(oldTitles);
for (User user : users) {
for (Issue issue : issues) {
if (user.getKey().equals(issue.getTitle())) {
issue.setTitle(user.getFirstName() + " " + user.getLastName());
}
}
}
Is there any other way to write this ?
Upvotes: 0
Views: 58
Reputation: 37645
It's quite hard to follow exactly what's going on here, but there are 2 improvements I can spot.
Firstly, there is no point in userIssues
at all (although it seems odd that in the last step you iterate over all issues
rather than userIssues
. Is this right?). Just do
List<String> oldTitles = issues
.stream()
.filter(a -> a.getIssueElement() == IssueElementEnum.USER)
.map(Issue::getTitle)
.collect(Collectors.toList());
Secondly, the nested loops appear unnecessary. I'm not 100% clear on your logic but something like this ought to work.
Map<String, User> usersByKey = new HashMap<>();
for (User user : users)
usersByKey.put(user.getKey(), user);
for (Issue issue : issues) {
User user = usersByKey.get(issue.getTitle());
if (user != null)
issue.setTitle(user.getFirstName() + " " + user.getLastName());
}
Upvotes: 1