classlib: add not method to Predicate interface (#709)

With this addition the Predicate interface is 100% complete for Java 17.
This commit is contained in:
Jasper Siepkes 2023-06-07 12:57:22 +02:00 committed by GitHub
parent 9dd9fc3a8a
commit efe15e323b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 79 additions and 1 deletions

View File

@ -33,7 +33,11 @@ public interface TPredicate<T> {
return t -> test(t) || other.test(t); return t -> test(t) || other.test(t);
} }
default TPredicate<T> isEqual(Object targetRef) { static <T> TPredicate<T> isEqual(Object targetRef) {
return t -> TObjects.equals(t, targetRef); return t -> TObjects.equals(t, targetRef);
} }
static <T> TPredicate<T> not(TPredicate<? super T> target) {
return (TPredicate<T>) target.negate();
}
} }

View File

@ -0,0 +1,74 @@
/*
* Copyright 2023 Jasper Siepkes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.classlib.java.util.function;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.function.Predicate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
import org.teavm.junit.WholeClassCompilation;
@RunWith(TeaVMTestRunner.class)
@WholeClassCompilation
public class PredicateTest {
@Test
public void andWorks() {
Predicate<Integer> greaterThenFour = x -> x > 4;
Predicate<Integer> greaterThenEight = x -> x > 8;
assertTrue(greaterThenFour.and(greaterThenEight).test(10));
assertFalse(greaterThenFour.and(greaterThenEight).test(6));
}
@Test
public void negateWorks() {
Predicate<Integer> greaterThenFour = x -> x > 4;
assertFalse(greaterThenFour.negate().test(10));
assertTrue(greaterThenFour.negate().test(1));
}
@Test
public void orWorks() {
Predicate<Integer> smallerThenFour = x -> x < 4;
Predicate<Integer> greaterThenEight = x -> x > 8;
assertTrue(smallerThenFour.or(greaterThenEight).test(3));
assertFalse(smallerThenFour.or(greaterThenEight).test(6));
assertTrue(smallerThenFour.or(greaterThenEight).test(9));
}
@Test
public void isEqualWorks() {
Predicate<Integer> isThree = Predicate.isEqual(3);
assertFalse(isThree.test(2));
assertTrue(isThree.test(3));
assertFalse(isThree.test(4));
}
@Test
public void notWorks() {
Predicate<Integer> isThree = x -> x == 3;
assertTrue(Predicate.not(isThree).test(2));
assertFalse(Predicate.not(isThree).test(3));
assertTrue(Predicate.not(isThree).test(4));
}
}