0

I have 2 list for Organizations, one that followed by users and another is the all Organizations in the database, I made 2 loops inside each others to set the value of followed for original list with true if user following this organization (that can be known from user organizations list)

List<Organization> organizationList = getServiceInstance().getOrganizationService().findOrganizationList();
List<Organization> organizations = getServiceInstance().getOrganizationService().findFollowedOrganizationList(userId);
for (Organization fOrg: organizations) {
    for (Organization organization : organizationList) {
        if (Objects.equals(fOrg.id, organization.id)) {
            fOrg.followed = true;
        }
    }
}

I believe there is better way to do this.

Al-Mothafar
  • 7,949
  • 7
  • 68
  • 102

3 Answers3

2

Try to use a map id->organization. That way you'd have 2 non-nested loops, one for building the map and one to loop over organizations and match the objects.

Example:

//build the map
Map<Integer, Organization> orgsInDB = new HashMap<>();
for( Organization org : organizationList ) {
  orgsInDB.put(org.getId(), org );
}

//match
for( Organization org : organizations ) {
  Organization orgInDB = orgsInDB.get( org.getId() );
  if( orgInDB != null ) {
    orgInDB.setFollowed( true );
  }
}

The complexity for this drops from O(n*m) to O(n + m).

Edit: As Al-Mothafar correctly pointed out we should consider the worst case which would be following all organizations. Thus complexity of his approach would be O(n2) while the approach above would be O(n+n) (or, since constant factors are generally left out in big-oh notation, just O(n)).

Thomas
  • 87,414
  • 12
  • 119
  • 157
1

I have used CollectionUtils from Apache commons library. It has static intersection, union and subtract methods which are suitable for your case as well. Pretty neat as well.

Nicely explained here with relation to set theory :)

Sheetal Mohan Sharma
  • 2,908
  • 1
  • 23
  • 24
0

I don't think, that there is a better way to do this, at least not in terms of performance: You've got to iterate over the organizations somewhere. Readability could be improved by packaging some lines into a private method.

The only suggestion I have is that you might replace Organization.followed (boolean) with Organization.followers (List). If so, you could simply check, whether the list is empty, or not. OTOH, this might slow down database accesses.

user1774051
  • 843
  • 1
  • 6
  • 18
  • 2
    Of course there is a better way in terms of performance :) - The code above has O(n*m) complexity which is unnecessary. – Thomas Mar 08 '16 at 11:54