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

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

[no_toc]
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!

90 thoughts on “Java – How to find an element in a Java List Object by Examples”

  1. Hey there! I realize this is kind of off-topic however I needed
    to ask. Does operating a well-established blog such as yours take a massive amount work?
    I am brand new to blogging but I do write in my diary everyday.

    I’d like to start a blog so I will be able to share my experience and views online.
    Please let me know if you have any kind of suggestions or tips for new aspiring blog owners.
    Appreciate it!

  2. Thank you for some other informative website. Where else could I get that kind of
    info written in such a perfect way? I have a challenge that
    I am simply now running on, and I have been at the glance
    out for such info.

  3. I think this is one of the most important information for me.

    And i am glad reading your article. But wanna remark on some general things, The web site style
    is wonderful, the articles is really nice : D.
    Good job, cheers

  4. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet
    my newest twitter updates. I’ve been looking for a plug-in like this for
    quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.

    I truly enjoy reading your blog and I look forward to your
    new updates.

  5. I do accept as true with all the concepts you’ve offered in your post.
    They’re very convincing and can certainly work. Still, the posts are too short for
    starters. Could you please lengthen them a bit
    from next time? Thanks for the post.

  6. I gɡot thіs ᴡeb age from mmy buddy who shared ѡith
    me reցading thiѕ sit and ɑt the moment this timе I am visiting this site ɑnd reading vesry infoгmative
    articles аt this time.

  7. I like the valuable information you provide in your articles.

    I’ll bookmark your blog and check again here frequently.
    I am quite certain I’ll learn a lot of new stuff right here!
    Best of luck for the next!

  8. Wow that was strange. I just wrote an very long comment but after I clicked submit my comment
    didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say superb blog!

  9. I know this if off topic but I’m looking into starting my own blog and
    was curious what all is required to get set up?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% certain. Any recommendations
    or advice would be greatly appreciated. Many thanks

  10. Aw, this was an extremely nice post. Taking the time and actual
    effort to make a really good article… but what can I say…
    I hesitate a whole lot and never manage to get anything done.

  11. Having read this I thought it was extremely enlightening. I appreciate you taking
    the time and effort to put this content together.
    I once again find myself personally spending a lot of time both reading and leaving comments.
    But so what, it was still worth it!

  12. I am really inspired along with your writing skills and also with the format
    on your blog. Is that this a paid subject matter or did
    you modify it yourself? Either way keep up the excellent quality writing, it’s rare to look a
    great blog like this one these days..

  13. hello!,I like your writing so so much! percentage we communicate extra approximately your post on AOL?
    I need an expert in this space to unravel my problem. Maybe that’s you!
    Taking a look forward to peer you.

  14. Howdy! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.
    If you know of any please share. Thanks!

  15. Excellent post. I was checking continuously this blog and I’m impressed!
    Extremely useful info specifically the last part :
    ) I care for such info a lot. I was seeking this particular info for a long time.
    Thank you and good luck.

  16. Have you ever thought about writing an e-book or guest authoring on other blogs?

    I have a blog based upon on the same subjects you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work.
    If you are even remotely interested, feel free to shoot me an e
    mail.

  17. Hi, i think that i noticed you visited my website so i got
    here to return the favor?.I’m trying to to find issues to improve my web site!I assume its ok to use some of your
    ideas!!

  18. Hi, i think that i noticed you visited my web site thus i came
    to go back the want?.I am attempting to in finding things to enhance my site!I assume its adequate to use some of
    your ideas!!

  19. Hello! I could have sworn I’ve been to this blog before but after reading through some of
    the post I realized it’s new to me. Nonetheless, I’m definitely glad I found it
    and I’ll be bookmarking and checking back frequently!

  20. I’m not that much of a online reader to be honest
    but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come
    back down the road. All the best

  21. Very good site you have here but I was curious if you knew of any community forums that cover the same topics talked
    about here? I’d really like to be a part of group where I can get advice from
    other experienced individuals that share the same interest.
    If you have any recommendations, please let me know. Thank you!

  22. For most recent information you have to visit the web and on internet I found this web page as a
    most excellent website for most up-to-date updates.

  23. Simply want to say your article is as astonishing. The
    clarity in your post is just excellent and i could
    assume you are an expert on this subject. Fine with your permission allow
    me to grab your RSS feed to keep up to date with forthcoming
    post. Thanks a million and please carry on the enjoyable work.

  24. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this website?

    I’m getting fed up of WordPress because I’ve had problems with hackers and I’m
    looking at options for another platform. I would be fantastic if you could point me in the direction of
    a good platform.

  25. Right here is tһe perfecct webpage foг anyone who really wants to find
    оut about this topic. Уou realize a whole lot itѕ almost
    hard to aгgue with you (not thаt I personally would want to…HaHa).

    You certainly put a Ьrand new spin on a topic wһich hаs been discussed for decaⅾes.
    Excelpent stuff, just excellent!

  26. Thank you for the good writeup. It in truth was once a enjoyment account it.
    Glance complex to more delivered agreeable from you! However, how can we communicate?

  27. An outstanding share! I have just forwarded this
    onto a co-worker who was conducting a little homework on this.
    And he in fact bought me dinner due to the
    fact that I stumbled upon it for him… lol. So let me reword this….
    Thanks for the meal!! But yeah, thanks for spending
    some time to talk about this issue here on your internet site.

  28. I’m curious to find out what blog platform you’re working with?
    I’m experiencing some minor security problems with my latest website and I’d like to find something more secure.
    Do you have any suggestions?

  29. Simply want to say your article is as astonishing.
    The clearness in your submit is simply excellent and that i can think you’re an expert on this subject.
    Well along with your permission let me to seize your RSS feed to stay up to date with imminent post.
    Thank you a million and please keep up the enjoyable work.

  30. Attractive cօmⲣonent off content. I simply stumbled upon your site and
    in accession capital to claim that I acquire actսally enjoyed
    ɑccount your blog posts. Any way I’ll be subscrіbing on ypur feeds oг even I acһievement you get
    entry too сonsistently rapidly.

  31. An interesting discussion is definitely worth comment. I think that you
    ought to publish more on this topic, it may not be a taboo matter but generally people don’t speak about these issues.
    To the next! Best wishes!!

  32. Magnificent goods from you, man. I have understand your stuff previous to and
    you’re just too fantastic. I actually like what you have acquired here, really like what you’re saying and
    the way in which you say it. You make it entertaining and you still take care of to keep
    it smart. I can not wait to read far more from you.
    This is actually a tremendous site.

  33. Generally I don’t read article on blogs, however I wish to say that
    this write-up very compelled me to take a look at and do so!
    Your writing taste has been amazed me. Thanks, very nice post.

  34. you’re in reality a excellent webmaster. The web site loading pace is incredible. It kind of feels that you are doing any unique trick. In addition, The contents are masterwork. you have performed a wonderful task on this matter!

  35. Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create
    my own. Do you require any coding expertise to make your own blog?
    Any help would be greatly appreciated!

  36. I’m curious to find out what blog platform you happen to be using?
    I’m having some small security issues with my latest blog and I would like to find something more safeguarded.
    Do you have any recommendations?

  37. Great article! This is the type of information that are supposed to be shared around
    the net. Shame on the seek engines for not positioning this
    put up upper! Come on over and talk over with my web site .

    Thanks =)

  38. Unquestionably believe that which you stated. Your favorite reason appeared to be on the internet the
    simplest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly do not know about.
    You managed to hit the nail upon the top as well as defined out
    the whole thing without having side effect , people could take a signal.
    Will likely be back to get more. Thanks

  39. You’re so interesting! I don’t suppose I’ve read a single thing
    like that before. So nice to discover someone with some unique thoughts on this issue.
    Really.. thanks for starting this up. This website is something that’s needed on the internet, someone with a little originality!

  40. I’ve been browsing online more than three hours today, yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all
    website owners and bloggers made good content as you did, the
    internet will be a lot more useful than ever before.

  41. Pretty great post. I simply stumbled upon your blog
    and wished to mention that I’ve truly loved browsing your weblog
    posts. In any case I will be subscribing to your feed and I hope you write again soon!

  42. I’ve been exploring for a little for any high quality articles or weblog posts in this kind of area .

    Exploring in Yahoo I at last stumbled upon this web site.
    Studying this info So i’m happy to express that I have an incredibly just right uncanny feeling I found out exactly what I needed.
    I most surely will make certain to do not forget this
    website and provides it a glance on a continuing basis.

  43. I am not sure where you’re getting your information,
    but great topic. I needs to spend some time learning more or understanding
    more. Thanks for great info I was looking for this info for
    my mission.

  44. Appreciating the hard work you put into your site and detailed information you
    offer. It’s awesome to come across a blog every once in a while that isn’t the same
    old rehashed information. Wonderful read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  45. Very nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed surfing around your weblog posts.

    In any case I will be subscribing on your rss feed and I
    am hoping you write once more soon!

  46. Howdy, i read your blog occasionally and i own a similar one and i was just curious if you get
    a lot of spam comments? If so how do you protect against it, any
    plugin or anything you can recommend? I get so much lately it’s driving me mad so
    any support is very much appreciated.

  47. You can certainly see your enthusiasm within the work you write.

    The arena hopes for even more passionate writers like you who aren’t afraid
    to say how they believe. All the time go after your heart.

  48. Hеy very nice blog!! Man .. Beautiful .. Suerb .. I’ll Ьookmark your blog аnd take the
    feeds alsօ? I am glad to seek outt a lоt of һelpful information here
    within the put սp, we’ⅾ like work out extra strategies in this regard, thanks ffor ѕharing.
    . . . . .

  49. Admiring the dedication you put into your site and in depth information you offer.
    It’s awesome to come across a blog every once in a while that isn’t the same old rehashed information. Excellent read!
    I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

  50. Thanks for your posting. I also believe that laptop computers have become more and more popular right now, and now in many cases are the only kind of computer found in a household. Simply because at the same time that they are becoming more and more reasonably priced, their computing power is growing to the point where they’re as potent as desktop through just a few years back.

  51. Nice post. I used to be checking constantly this weblog and I
    am inspired! Extremely helpful information specifically the last part 🙂
    I maintain such info much. I was looking for this particular information for a long time.
    Thank you and good luck.

Leave a Reply

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