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

Time:07-05

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?

CodePudding user response:

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));
}

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

CodePudding user response:

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));
}

CodePudding user response:

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

  • Related