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:

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

Example:

Example with Custom Object

– Define a Customer class:

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

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

indexOf()

Signature:

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

Example:

Looping to Find Element in Java List

– Example 1:

– Example 2 with Iterator implementation:

Use Stream Filter of Java 8

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

And combine with findFirst method. Detail Example:

Use Google Guava

– Dependency:

– Example:

Full code:

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.



Related Posts


Got Something To Say:

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

*