0

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 ?

1
  • 5
    Is there any other way to write this? Well, of course there is. What is the best (TM) depends on your problem: Quickest runtime, lowest memory consumption, for 10 or 100000 elements? Async or sync consumption of the result? Including or excluding preceding and following database operation? Etc. IMHO a highly subjective question. Commented Apr 2, 2018 at 15:45

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.