!1008 CollUtil新增anyMatch和allMatch方法

Merge pull request !1008 from gwml/v5-master
This commit is contained in:
Looly 2023-06-02 17:42:35 +00:00 committed by Gitee
commit 8432d76064
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 39 additions and 0 deletions

View File

@ -667,6 +667,36 @@ public class CollUtil {
return currentAlaDatas;
}
/**
* 是否至少有一个符合判断条件
*
* @param <T> 集合元素类型
* @param collection 集合
* @param predicate 自定义判断函数
* @return 是否有一个值匹配 布尔值
*/
public static <T>boolean anyMatch(Collection<T> collection,Predicate<T> predicate){
if(isEmpty(collection)){
return Boolean.FALSE;
}
return collection.stream().anyMatch(predicate);
}
/**
* 是否全部匹配判断条件
*
* @param <T> 集合元素类型
* @param collection 集合
* @param predicate 自定义判断函数
* @return 是否全部匹配 布尔值
*/
public static <T>boolean allMatch(Collection<T> collection,Predicate<T> predicate){
if(isEmpty(collection)){
return Boolean.FALSE;
}
return collection.stream().allMatch(predicate);
}
// ----------------------------------------------------------------------------------------------- new HashSet
/**

View File

@ -1057,4 +1057,13 @@ public class CollUtilTest {
final Object first = CollUtil.getFirst(nullList);
Assert.assertNull(first);
}
@Test
public void testMatch() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Assert.assertTrue(CollUtil.anyMatch(list, i -> i == 1));
Assert.assertFalse(CollUtil.anyMatch(list, i -> i > 6));
Assert.assertFalse(CollUtil.allMatch(list, i -> i == 1));
Assert.assertTrue(CollUtil.allMatch(list, i -> i <= 6));
}
}