1

I have an object with a list of contents in it and the other object with contents in it without the list like the code below

List<LoginInformation> allUsersLoginInfo
LoginInformation loginInformation

Now I want to compare these two and see if the elements of loginInformation exists in allUsersLoginInfo

LoginInformation is a model class.

It has Name and Rollnumber.

So, allUserLoginInfo is a list which contains multiple values for Name and Rollnumber.

Now, I want to compare and see if any value of loginInformation (i.e.,either the value of Name or RollNumber) presents in allUserLoginInfo then gives me true else false noting that no values are equal.

Thanks in advance

Vamsi
  • 619
  • 3
  • 9
  • 22

4 Answers4

0

You could do:

allUsersLoginInfo.contains(loginInformation);

but you need to override properly the equals method in the class LoginInformation, if not, the list will never find the element and will return false...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0
lUsersLoginInfo.contains(loginInformation)

Could be what you're looking for If there's a lot of info in the list I would suggest using a set instead. But you better not be saving the passwords in the user infos...

Ted Cassirer
  • 364
  • 1
  • 10
0

You can use Stream#anyMatch to accomplish the task at hand.

if(allUsersLoginInfo.stream().anyMatch(m -> m.getName().equals(loginInformation.getName())
                   || m.getRollNumber() == loginInformation.getRollNumber())){
        //exists
}else{
      // does not exist
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Hi, I tried this solution but getting ArrayOutOfBounds Exception. Please find the part of stack trace. java.lang.IndexOutOfBoundsException: Index: 11, Size: 1 java.util.ArrayList.rangeCheck(ArrayList.java:653) java.util.ArrayList.get(ArrayList.java:429) – Vamsi May 31 '17 at 15:18
  • the error is not from the code I've posted...must be somewhere else in your code. As you can clearly see from the code I am not indexing into anything. – Ousmane D. May 31 '17 at 15:22
  • My bad. I got it and fixed it. Thanks for the response. It worked for me – Vamsi May 31 '17 at 15:26
0

You could use Apache Commons for java prior to 1.8

This example find if any value of loginInformation (i.e.,either the value of Name or RollNumber) presents in allUserLoginInfo :

LoginInformation res = CollectionUtils.find(allUsersLoginInfo, new Predicate<LoginInformation >() {
        @Override
        public boolean evaluate(LoginInformation o) {
            return o.getName ().equals(yourloginInformation.getName()) ||  o.getRollnumber () == yourloginInformation.getRollnumber();
        }
    });

For java 1.8 use Aominè answer

Mike Adamenko
  • 2,944
  • 1
  • 15
  • 28