S.Dan
S.Dan

Reputation: 1912

Is there a way to use a common method to take Iterable of String and Long

I have the following 2 methods:

boolean iterableContainsStr(Iterable<String> iterable, Object matcher) {
        return StreamSupport.stream(iterable.spliterator(), false).anyMatch(i -> i.equals(matcher));
    }

boolean iterableContainsLong(Iterable<Long> iterable, Object matcher) {
        return StreamSupport.stream(iterable.spliterator(), false).anyMatch(i -> i.equals(matcher));
    }

The content is equal in both methods, and I tried to use the following:

boolean iterableContains(Iterable<Object> iterable, Object matcher) {
        return StreamSupport.stream(iterable.spliterator(), false).anyMatch(i -> i.equals(matcher));
    }

but it throws a compilation error when I try to use it with String or Long iterable. Any solution?

Upvotes: 1

Views: 76

Answers (3)

royB
royB

Reputation: 12977

The compile error is because your method expects a class Iterable of type String and you pass it a class Iterable of type Object.

Just use generics (or whildcard as suggested by @Stephen c)

<T> boolean  iterableContains(Iterable<T> iterable, Object matcher) {
    return StreamSupport.stream(iterable.spliterator(), false).anyMatch(i -> i.equals(matcher));
}

//or
boolean iterableContains(Iterable<?> iterable, Object matcher) {
 ...
}

and then

Iterable<String> iter = List.of("aaa");
System.out.println(iterableContains(iter, "aaa")); //true
System.out.println(iterableContains(iter, "bbb")); //false

Upvotes: 3

Ashish Patil
Ashish Patil

Reputation: 4604

boolean iteContains(Iterable<?> itr, Object matcher) {
        return StreamSupport.stream(itr.spliterator(), false).anyMatch(i -> i.equals(matcher));
    }

You can use ? wildcard type in your method

Upvotes: 0

DEV
DEV

Reputation: 1726

You can try use generic method, matcher also should be T :

static <T> boolean iterableContains2(Iterable<T> iterable, T matcher) {
    return StreamSupport.stream(iterable.spliterator(), false).anyMatch(i -> i.equals(matcher));
}

Upvotes: 0

Related Questions