Java check item in list

Check if one list contains element from the other

I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame). right now, I do it like this:

boolean found = false; for(Object1 object1 : list1) < for(Object2 object2: list2)< if(object1.getAttributeSame() == object2.getAttributeSame())< found = true; //also do something >> if(!found) < //do something >found = false; > 

stackoverflow.com/questions/5187888/…. Moreover, for speedy search try using Binary Search and change your DS to suite the situation.

11 Answers 11

If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

!Collections.disjoint(list1, list2); 

If you need to test a specific property, that’s harder. I would recommend, by default,

list1.stream() .map(Object1::getProperty) .anyMatch( list2.stream() .map(Object2::getProperty) .collect(toSet()) ::contains) 

. which collects the distinct values in list2 and tests each value in list1 for presence.

Also, please note that, for lists, this will be O(n*m); if you’re willing to copy list1 into a Set before comparing, you’ll get O(n) + O(m), that is, O(n+m), at the cost of some extra RAM; it’s a matter of choosing between speed or memory.

Читайте также:  Qt designer python lineedit

This would work only if «List list1; List list2″ but not on two different objects or datatypes like Listlist1; Listlist2.

Ofcourse this will not work for those scenarios @Zephyr , for the question asked, it works perfect as long as you have right equals implemented. that’s all matters!

To shorten Narendra’s logic, you can use this:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element)); 
if(CollectionUtils.containsAny(list1,list2)) < // do whatever you want >else < // do other thing >

This assumes that you have properly overloaded the equals functionality for your custom objects.

@ohcibi Java also has a built in logger, you should go downvote people that suggest to use Log4j and Log4j2 while you are at it.

@Woot4Moo it depends. There is no reason to downvote if there is a reason to use Log4j to solve the OPs problem. In this case apache commons would simply be useless bloat like in 99% of the answers that suggest apache commons.

@ohcibi but if you already are using Apache commons then it is not really bloat. This was a good answer.

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

boolean b = list1.retainAll(list2); 

Loius answer is correct, I just want to add an example:

listOne.add("A"); listOne.add("B"); listOne.add("C"); listTwo.add("D"); listTwo.add("E"); listTwo.add("F"); boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true 

I think if you add element ‘A’ to second list listTwo.add(«A»); even though Collections.disjoint(listOne, listTwo); returns true.

Returns: true if the two specified collections have no elements in common. (c) if two collection have at least 1 common element > False else True doesn’t matter how much elements they have.

faster way will require additional space .

  1. put all items in one list into a HashSet ( you have to implement the hash function by yourself to use object.getAttributeSame() )
  2. Go through the other list and check if any item is in the HashSet.

In this way each object is visited at most once. and HashSet is fast enough to check or insert any object in O(1).

According to the JavaDoc for the .contains(Object obj) :

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

So if you override your .equals() method for your given object, you should be able to do: if(list1.contains(object2)).

If the elements will be unique (ie. have different attributes) you could override the .equals() and .hashcode() and store everything in HashSets . This will allow you to check if one contains another element in constant time.

Источник

How to Find an Element in a List with Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

Finding an element in a list is a very common task we come across as developers.

In this quick tutorial, we’ll cover different ways we can do this with Java.

Further reading:

Checking If a List Is Sorted in Java

Java List Initialization in One Line

2. Setup

First let’s start by defining a Customer POJO:

List customers = new ArrayList<>(); customers.add(new Customer(1, "Jack")); customers.add(new Customer(2, "James")); customers.add(new Customer(3, "Kelly")); 

Note that we’ve overridden hashCode and equals in our Customer class.

Based on our current implementation of equals, two Customer objects with the same id will be considered equal.

We’ll use this list of customers along the way.

3. Using Java API

Java itself provides several ways of finding an item in a list:

3.1. contains()

List exposes a method called contains:

boolean contains(Object element)

As the name suggests, this method returns true if the list contains the specified element, and returns false otherwise.

So when we need to check if a specific item exists in our list, we can:

Customer james = new Customer(2, "James"); if (customers.contains(james)) < // . >

3.2. indexOf()

indexOf is another useful method for finding elements:

int indexOf(Object element)

This method returns the index of the first occurrence of the specified element in the given list, or -1 if the list doesn’t contain the element.

So logically, if this method returns anything other than -1, we know that the list contains the element:

if(customers.indexOf(james) != -1) < // . >

The main advantage of using this method is that it can tell us the position of the specified element in the given list.

3.3. Basic Looping

Now what if we want to do a field-based search for an element? For example, say we’re announcing a lottery and we need to declare a Customer with a specific name as the winner.

For such field-based searches, we can turn to iteration.

A traditional way of iterating through a list is to use one of Java’s looping constructs. In each iteration, we compare the current item in the list with the element we’re looking for to see if it’s a match:

public Customer findUsingEnhancedForLoop( String name, List customers) < for (Customer customer : customers) < if (customer.getName().equals(name)) < return customer; >> return null; >

Here the name refers to the name we are searching for in the given list of customers. This method returns the first Customer object in the list with a matching name, or null if no such Customer exists.

3.4. Looping With an Iterator

Iterator is another way that we can traverse a list of items.

We can simply take our previous example and tweak it a bit:

public Customer findUsingIterator( String name, List customers) < Iteratoriterator = customers.iterator(); while (iterator.hasNext()) < Customer customer = iterator.next(); if (customer.getName().equals(name)) < return customer; >> return null; >

Consequently, the behavior is the same as before.

3.5. Java 8 Stream API

As of Java 8, we can also use the Stream API to find an element in a List.

To find an element matching specific criteria in a given list, we:

  • invoke stream() on the list
  • call the filter() method with a proper Predicate
  • call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists
Customer james = customers.stream() .filter(customer -> "James".equals(customer.getName())) .findAny() .orElse(null);

For convenience, we default to null in case an Optional is empty, but this might not always be the best choice for every scenario.

4. Third-Party Libraries

Now, while the Stream API is more than sufficient, what should we do if we’re stuck on an earlier version of Java?

Fortunately, there are many third-party libraries like Google Guava and Apache Commons which we can use.

4.1. Google Guava

Google Guava provides functionality that is similar to what we can do with streams:

Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).orNull();

Just like with Stream API, we can optionally choose to return a default value instead of null:

Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).or(customers.get(0));

The above code will pick the first element in the list if no match is found.

Also, don’t forget that Guava throws a NullPointerException if either the list or the predicate is null.

4.2. Apache Commons

We can find an element in almost the exact same way using Apache Commons:

Customer james = IterableUtils.find(customers, new Predicate() < public boolean evaluate(Customer customer) < return "James".equals(customer.getName()); >>);

There are a couple of important differences though:

  1. Apache Commons just returns null if we pass a null list.
  2. It doesn’t provide default value functionality like Guava’s tryFind.

5. Conclusion

In this article, we learned different ways of finding an element in a List, starting with quick existence checks and finishing with field-based searches.

We also looked at the third-party libraries Google Guava and Apache Commons as alternatives to the Java 8 Streams API.

Thanks for stopping by, and remember to check out all the sources for these examples over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью