简体   繁体   中英

Best way to modify objects in list using values from another list

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 ?

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());
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM