1

I have a List<String> I need to find whether the particular string exists inside a List or not.

for Eg:

String str = "apple";

List<String> listObject = Lists.newArrayList("apple", "orange", "banana");

I need to find whether str exists in listObject or not using Google Guava.

So I need a true or false result.

How can I achieve this?

Gnik
  • 7,120
  • 20
  • 79
  • 129

2 Answers2

18

This is a standard part of the Java Collections API:

boolean exists = listObject.contains(str);
Stewart
  • 17,616
  • 8
  • 52
  • 80
  • I think I misunderstood the question. – Stewart Jan 30 '14 at 18:05
  • 1
    I don't think you did. – ColinD Jan 30 '14 at 19:53
  • The question was specifically asking how to do it using Guava, and I missed that point. `FluentIterable.contains()` calls `Iterables.contains()` which logic is different, including suppressing `NullPointerException` – Stewart Jan 31 '14 at 04:25
  • 1
    Yeah, the thing is that there is no good reason to want to do this _using Guava_ when the way one _should_ do this (as you pointed out) exists in the standard APIs. And the behavior of throwing `NPE` from `Collection.contains(null)` is rare enough (I'm not sure I know of any implementations that actually do that) that no one should be using `FluentIterable.contains` _just_ for that unless they know it's something they need to worry about. And `ArrayList` doesn't do that anyway. – ColinD Jan 31 '14 at 17:04
4

I'm agree that this can be done (and should, maybe) with the standard Collections API, but anyway, in Guava you can do it like this:

List<String> strList = Arrays.asList(new String[] {"one", "two", "3", "4"});
boolean exists = FluentIterable.from(strList).contains("two");
yamilmedina
  • 3,315
  • 2
  • 20
  • 28
  • 8
    You could even replace `.contains("two")` by `.anyMatch(Predicates.equalTo("two"))` for a bit more obfuscation. – Frank Pavageau Jan 30 '14 at 13:31
  • The main difference between this solution and the Collections API is that this solution works on any `Iterable`. In other words, the `Arrays.asList()` part is redundant. Just pass the array straight in. – Stewart Jan 30 '14 at 18:08
  • 1
    @Stewart: Arrays are not `Iterable`, unfortunately. Plus, you can write `Arrays.asList(array).contains("two")` if all you need is the contains check. – ColinD Jan 31 '14 at 17:06
  • Dah! Shorthand `for` loop strikes again! http://stackoverflow.com/questions/1160081/why-is-an-array-not-assignable-to-iterable – Stewart Jan 31 '14 at 17:15