1

I have a list of institutionUserConnections and I will have the users. Therefore I iterate over the institutionUserConnections list. It can be that a user is in more than one institution. Therefore I have 2 different user object - but it is the same user.

My question now would be how to get a unique list of users?

final List<User> users = new ArrayList<>();
    for (final InstitutionUserConnection institutionUserConnection : institutionUserConnections) {
        final User user = institutionUserConnection.getUser();
        users.add(user);
    }

[EDIT] Actually it is hard to explain. I have also used a Set but with no success. Here is the whole code I use:

final List<InstitutionUserConnection> institutionUserConnectionsOfUser = institutionUserConnectionService
        .getActiveInstitutionUserConnectionsByUser(foundedUser);

    final List<InstitutionUserConnection> institutionUserConnections = new ArrayList<>();
    for (final InstitutionUserConnection institutionUserConnection : institutionUserConnectionsOfUser) {
        final Institution institution = institutionUserConnection.getInstitution();
        institutionUserConnections
            .addAll(institutionUserConnectionService.getActiveInstitutionUserConnectionsByInstitution(institution));
    }

    final List<User> users = new ArrayList<>();
    for (final InstitutionUserConnection institutionUserConnection : institutionUserConnections) {
        final User user = institutionUserConnection.getUser();
            users.add(user);
    }

Maybe someone have another hint how I can solve this issue.

quma
  • 5,233
  • 26
  • 80
  • 146
  • 2
    Use a `Set`, e.g. a [`HashSet`](http://docs.oracle.com/javase/8/docs/api/?java/util/HashSet.html). Or be more specific regarding your obstacles or why you tagged your question with `java-8` rather than `java`. – Holger Dec 22 '15 at 15:20
  • Can you elaborate on the idea that you 'have 2 different user object'? Do you mean you have more than 1 reference to the same (identical or equal) object in the list, or do you have multiple objects which have some common fields which are neither equal nor identical but which represent the same 'physical' person, or do you mean you have multiple objects of unrelated types but which might have the same name and again represent the same physical person? – sisyphus Dec 22 '15 at 16:22
  • Use Set, and esure that Uer Object has equals method overwritten. – vels4j Dec 23 '15 at 05:42

3 Answers3

1

as suggested in the comments user HashSet, which will retain only unique reference of the object.

I could not understand your question clearly. I have design a way to get around your issue I hope it helps

  1. class InstituteUserConnection holds insitute name and a list of Users.
  2. listOfInsituteUserConnection will hold InstituteUserConnection.
  3. Iterate over the listOfInsituteUserConnection and get Users and put them into Set<User>. you can check the count in the User to cross verify and print them out.
  4. FYI HashSet works on the principle of hashing check link for info.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

class User {

    String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof User)) {
            return false;
        }
        User objUser = (User) obj;
        System.out.println("in equals");
        return this.name.equals(objUser.getName());

    }

    @Override
    public String toString() {
        return this.name;
    }

}

public class InstitutionUserConnections {
    String institutionName;
    List<User> users;

    public InstitutionUserConnections(String institutionName, List<User> users) {
        this.users = users;
        this.institutionName = institutionName;
    }

    public void addUser(User user) {
        this.users.add(user);
    }

    public List<User> getUsers() {
        return this.users;
    }

    public static void main(String[] args) {
        User user1 = new User("user1");
        User user2 = new User("user2");

        List<InstitutionUserConnections> listOfInstitutionUserConnections = new ArrayList<InstitutionUserConnections>();
        List<User> institute1User = Arrays.asList(new User[] { user1, user2 });
        InstitutionUserConnections institute1 = new InstitutionUserConnections(
                "institute1", institute1User);

        List<User> institute2User = Arrays.asList(new User[] { user1 });
        InstitutionUserConnections institute2 = new InstitutionUserConnections(
                "institute1", institute2User);

        listOfInstitutionUserConnections.add(institute1);
        listOfInstitutionUserConnections.add(institute2);

        Set<User> listOfUniqueUsers = new HashSet<User>();
        for (InstitutionUserConnections institute : listOfInstitutionUserConnections) {
            listOfUniqueUsers.addAll(institute.getUsers());
        }

        System.out.println("No of User in Set<User> : "
                + listOfUniqueUsers.size());
        for (User user : listOfUniqueUsers) {
            System.out.println(user);
        }
    }
}
Dirk Fauth
  • 4,128
  • 2
  • 13
  • 23
saikumarm
  • 1,565
  • 1
  • 15
  • 30
  • 1
    Why people still use instanseof in Equals method.... kindly use if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; – usman Dec 23 '15 at 06:25
  • In the above example also the implementation of hashCode() is missing, which is bad practice in Java. But basically the answer is correct, you need to implement equals() and hashCode() to specify the equality of your objects to make the java.util.Set work the way you need. – Dirk Fauth Dec 23 '15 at 06:51
  • @DirkFauth i Have updated it. previously I was using the default inherited from Object class. but now I have changed it. I understand my hashfunction is not good. but it just an example. – saikumarm Dec 23 '15 at 06:53
  • 1
    @saikumarm Your hashCode implementation is not only not good, IMHO it is wrong. You should always use the same attribute for hashCode calculation that you are using for equality checks. That is the only way to make it right. The example is missing the null checks and more, but let's assume name can not be null. BTW, most of the IDE's provide functionality to create equals() and hashCode() based on attributes. I rarely think about writing them on my own. – Dirk Fauth Dec 23 '15 at 07:50
0

Try this

final HashSet<User> users = new HashSet<>();
for (final InstitutionUserConnection institutionUserConnection : institutionUserConnections) {
    final User user = institutionUserConnection.getUser();
        users.add(user);
}
// iterate users to check unique
vels4j
  • 11,208
  • 5
  • 38
  • 63
0

I would suggest to override your Equals method and use data structure you want to use,if you are eager to use List/ ArrayList or any set as well. Apache Commons Collection provide a great one line code to provide unique list.

Add Maven dependency or download jar :

<dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

Then simply use below line of code:

SetUniqueList uniqueList = SetUniqueList.decorate(<<Your list>>);

and override Equals and HashCode:

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

    YourClass tester = (YourClass) o;

    if (user!= null ? !user.equals(tester.user) : tester.user!= null) return false;


    return true;
}

@Override
public int hashCode() {
    int result = user != null ? user.hashCode() : 0;
    result = 31 * result + (anotherField!= null ? anotherField.hashCode() : 0);

    return result;
}
usman
  • 1,351
  • 5
  • 23
  • 47