Java – interpretation of V – > V > 5

I have a given function call, and Java gives me an error because the object cannot be compared with int (of course...) Can someone explain to me what I want to change?

I tried to support lambda expressions in different ways, but there were no useful results I think the lambda expression is correct and the filter function is a little wrong, but I can't find my error

// function call
filter(v -> v > 5)

// function
public Optional<T> filter(Predicate<T> tester) {
    if(isPresent() && tester.test(get())) {
        return this;
    } else {
    return Optional.empty();
    }
}

I look forward to an optional Empty object, but I get a Java error because V > 5 object v cannot be compared with int

Solution

You must make t a wrapper class equivalent to int for example

IntStream.range(0,10)
         .filter(v -> v > 5)
         .forEach(System.out::println);

Good, because V is an int

You cannot use this expression when t is unknown

What you can do is assume that t must be a number, for example

filter( v -> ((Number) v).doubleValue() > 5)

But this will produce a classcast expectation, and t is another type

The real solution is to make t a number

for example

class MyClass<T extends Number> {
    public Optional<T> filter(Predicate<T> test) {

Or make it a specific type like int

class MyClass {
    public IntOptional filter(IntPredicate test) {
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>