1

I need to check if an object present in list A exists in list B without using nested for loops because if the lists have a large size, it takes too much time.

This is my code :

for(Person el : persons)
{
    for(Client in : clients)
    {
        if(el.getIdentifier() == in.getTire().getIdentifier())
        {
            exists=true;
            break;
        }
    }
}

How can i achieve the same result without using loops and break?

7
  • Any object or do you know which object you want to search? From your code it seems to be any object, but just to be sure. Commented Oct 15, 2021 at 9:23
  • 1
    Why are you trying to achieve this without using loops and break ? Commented Oct 15, 2021 at 9:24
  • You will need to loop through both lists one way or another, but the loops don't have to be nested though. Commented Oct 15, 2021 at 9:25
  • What i'm asking for is to get the same result using another method like anyMatch, sorry about the wrong tag and no it's not homework , i'm trying to optimize the code. Commented Oct 15, 2021 at 9:48
  • 2
    @MauricePerry you should undelete your answer Commented Oct 15, 2021 at 10:22

5 Answers 5

3

Maybe you can do it like this

Set<String> identifierSet = new HashSet<>();

for (Person el : persons) {
    identifierSet.add(el.getIdentifier());
}

for (Client in : clients) {
    if (identifierSet.contains(in.getTire().getIdentifier())) {
        exists = true;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to get rid of the for loops and use anyMatch or something like that.
1

This will change the complexity of your code from O(NxM) to O(N+M):

    Set<Integer> personIds = persons.stream()
            .map(e -> e.getIdentifier())
            .collect(Collectors.toCollection(HashSet::new));

    boolean exists = clients.stream().anyMatch(
            c -> personIds.contains(c.getTire().getIdentifier()));

2 Comments

Good Answer. The Question mentions a large number of objects. I wonder if using a ConcurrentSkipListSet instead of HashSet might give better performance.
@BasilBourque I doubt it: the access time for a skiplist is in O(log(n)) instead of O(1) for a hash table.
1

You can improve performance by using data structures better suited for fast lookups. If you store clients in a HashMap where the key is the identifier, and the value is the client object then your code becomes:

for(Person el : persons)
{
    if (clients.containsKey(el.getIdentifier()) {
      exists=true;
    }
}

Now you only have one loop, and the cost of looking up in the hashmap is O(1).

Comments

1

As anyMatch is mentioned, the following solution based on Stream API can be offered (assuming the type of identifiers is String):

// prepare set of identifiers in clients
Set<String> clientIds = clients
    .stream()                                // Stream<Client>
    .map(in -> in.getTire().getIdentifier()) // Stream<String> client ids
    .collect(Collectors.toSet());

boolean anyPersonIsClient = persons
   .stream()                    // Stream<Person>
   .map(Person::getIdentifier)  // Stream<String> person identifiers
   .anyMatch(clientIds::contains);

boolean allPersonsAreClient = persons
   .stream()                    // Stream<Person>
   .map(Person::getIdentifier)  // Stream<String> identifiers
   .allMatch(clientIds::contains);

Comments

0

What about a classical :

contains(Object o) //Returns true if this list contains the specified element.

So you could just do loop instead :

for(Person el : persons)
{

        if(clients.contains(el.getIdentifier()))
        {
            exists=true;
            break;
        }        
}

But looking at your code, and depending on what you're aiming for, you could use:

containsAll(Collection c)
       //   Returns true if this list contains all of the elements of the specified collection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.