Avoiding nested for loops in iterating through complex objects
<p>I have a match table in my app which holds the details of the matches scheduled</p>

<p><a href="https://i.stack.imgur.com/0bnlA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0bnlA.png" alt="enter image description here"></a></p>

<p>I have a <code>user</code> table &amp; a <code>user_match</code> table which is a bridge table.</p>

<p><code>user_match</code> table below specifies info on which user follows which match &amp; supports which team.
<a href="https://i.stack.imgur.com/1gBEZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1gBEZ.png" alt="enter image description here"></a></p>

<p>Now in my controller method I am returning today's scheduled matches &amp; also check at the same time if the loggedIn user follows the today's scheduled matches.</p>

<p>The problem is I have to run two nested for loops in the process Complexity O(n^2). First I iterate through the current day matches &amp; then for every current day match I iterate through all the matches the user follows &amp; check if the current match is present. I was hoping if I could get rid of the nested for loop, could there be a better way to deal with this. </p>

<pre><code>@RequestMapping(value="/getTodaysMatches", method=RequestMethod.GET, consumes = "application/json", produces = "application/json")
public @ResponseBody List&lt;Match&gt; getMatchesForCurrentDate(){
    logger.debug("inside /getTodaysMatches CricketController method");

    DateTime currentServerTimeStamp = CricketUtil.getServerDateTime();
    List&lt;Match&gt; currentDayMatchList = this.cricketService.fetchMatchesForInputDate(currentServerTimeStamp);
    CustomUserDetail myUserDetails = currentUserAccessor.getCurrentLoggedInUser();
    User loggedInUser = myUserDetails.getUser();
    List&lt;UserMatchInfo&gt; userMatchInfoList = this.cricketService.getUserMatchInfoByUserId(loggedInUser.getUserId());

    /*check if the logged in user already follows matches scheduled for today*/

    for(Match  todaysMatch : currentDayMatchList){
        for(UserMatchInfo tmpUserMatchInfo : userMatchInfoList){
            String teamFollowedByUser = tmpUserMatchInfo.getSupportingTeam();
            Match matchWhichUserFollows = tmpUserMatchInfo.getMatch();
        if((matchWhichUserFollows.getMatchId().intValue()) == (todaysMatch.getMatchId().intValue())){
            todaysMatch.setLoggedInUserFollowsThisMatch(true);
        }

        if((todaysMatch.getTeamOne().equals(teamFollowedByUser))){
            todaysMatch.setLoggedInUserSupportsTeamOne(true);
        }

        if((todaysMatch.getTeamTwo().equals(teamFollowedByUser))){
            todaysMatch.setLoggedInUserSupportsTeamTwo(true);
        }
      }
    }

    return currentDayMatchList;
}
</code></pre>