Java – How to find an element in a Java List Object by Examples

java-tutorial-find-an-element-in-java-list-objects


In the tutorial, we will show how to find an element in a List Object with Java APIs and Google Guava library.

contains()

Signature method:


boolean java.util.List.contains(Object o)

-> Returns true if the list contains at least one element e such that Objects.equals(o, e).

Example:


List integerList = Arrays.asList(1, 3, 7, 9, 11);

System.out.println(integerList.contains(3));
// true

System.out.println(integerList.contains(4));
// false

Example with Custom Object

– Define a Customer class:


class Customer{
	private int id;
	private String name;
	
	Customer(int id, String name){
		this.id = id;
		this.name = name;
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	...
	
}

– We also need define equals() method for Customer class as below to compare Objects:


public boolean equals(Object o) { 

	// If the object is compared with itself then return true   
	if (o == this) { 
		return true; 
	} 

	/* Check if o is an instance of Customer or not 
	  "null instanceof [type]" also returns false */
	if (!(o instanceof Customer)) { 
		return false; 
	} 
	  
	// typecast o to Customer so that we can compare data members  
	Customer c = (Customer) o; 
	  
	// Compare the data members and return accordingly
	if(id == c.id && name.equals(c.name)) return true;
	else return false;
}

-> Now we do an example using contains() method with custom object list as below:


List customers = Arrays.asList(new Customer(1, "Jack"),
										new Customer(2,  "Mary"),
										new Customer(3, "Harry"),
										new Customer(4, "Joe"),
										new Customer(5, "Jane"));

System.out.println(customers.contains(new Customer(2, "Mary")));
// true

System.out.println(customers.contains(new Customer(3, "Jane")));
// false

indexOf()

Signature:


int java.util.List.indexOf(Object o)

indexOf returns the lowest index i such that Objects.equals(o, get(i)), or -1 if there is no such index.

Example:


List customers = Arrays.asList(new Customer(1, "Jack"),
										new Customer(2,  "Mary"),
										new Customer(3, "Harry"),
										new Customer(4, "Joe"),
										new Customer(5, "Jane"));

int index = customers.indexOf(new Customer(3, "Harry"));
System.out.println(index);
// 2

index = customers.indexOf(new Customer(7, "Mary"));
System.out.println(index);
// -1

Looping to Find Element in Java List

– Example 1:


public static void main(String[] args) {		
	List customers = Arrays.asList(new Customer(1, "Jack"),
											new Customer(2,  "Mary"),
											new Customer(3, "Harry"),
											new Customer(4, "Joe"),
											new Customer(5, "Jane"));
	
	Customer cust = findCustomer("Joe", customers);
	
	System.out.println("Customer id=" + cust.getId() + ", name=" + cust.getName());
	//Customer id=4, name=Joe
}

public static Customer findCustomer(String name, List customers) {
	for(Customer c: customers) {
		if(name.equals(c.getName())) {
			return c;
		}
	}
	return null;
}

– Example 2 with Iterator implementation:


public static Customer findCustomer(String name, List customers) {
	Iterator iterator = customers.iterator();
	while(iterator.hasNext()) {
		Customer c = iterator.next();
		if(c.getName().equals(name)) {
			return c;
		}
	}
	return null;
}

Use Stream Filter of Java 8

We use Predicate to filter an element with Java 8 Stream:


java.util.stream.Stream.filter(Predicate predicate)

And combine with findFirst method. Detail Example:


List customers = Arrays.asList(new Customer(1, "Jack"),
										new Customer(2,  "Mary"),
										new Customer(3, "Harry"),
										new Customer(4, "Joe"),
										new Customer(5, "Jane"));

Customer cust = customers.stream().filter(c -> c.getName() == "Joe").findFirst().orElse(null);

System.out.println("Customer id = " + cust.getId() + ", name = " + cust.getName());
// Customer id = 4, name = Joe

Use Google Guava

– Dependency:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.1-jre</version>
</dependency>

– Example:


Customer cust = Iterables.find(customers, new Predicate() {
      public boolean apply(Customer customer) {
          return "Jane".equals(customer.getName());
      }
  }, null);

Full code:


public static void main(String[] args) {		
	List customers = Arrays.asList(new Customer(1, "Jack"),
											new Customer(2, "Mary"),
											new Customer(3, "Harry"),
											new Customer(4, "Joe"),
											new Customer(5, "Jane"));
	
	Customer c = Iterables.find(customers, new Predicate() {
	      public boolean apply(Customer customer) {
	          return "Jane".equals(customer.getName());
	      }
	  }, null);

	if(null!=c){
		System.out.println("Customer id = " + cust.getId() + ", name = " + cust.getName());
	}
	// Customer id = 5, name = Jane
}

Conclusion

We had learned the way to find an element in Java Object List with Examples by using:

  • contains()
  • indexOf()
  • Looping to find Element
  • Use Stream Filter of Java 8
  • Google Guava

Happy learning! See you later!



By grokonez | April 1, 2019.

Last updated on April 19, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*