Merge pull request #1986 from scruel/dev-coll

 add removeWithAddIf methods
This commit is contained in:
Golden Looly 2021-11-30 11:42:38 +08:00 committed by GitHub
commit 6cb86ce509
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 0 deletions

View File

@ -1291,6 +1291,46 @@ public class CollUtil {
return filter(collection, StrUtil::isNotBlank);
}
/**
* 移除集合中的多个元素并将结果存放到指定的集合
* 此方法直接修改原集合
*
* @param <T> 集合类型
* @param <E> 集合元素类型
* @param resultCollection 存放移除结果的集合
* @param targetCollection 被操作移除元素的集合
* @param filter 用于是否移除判断的过滤器
*/
public static <T extends Collection<E>, E> T removeWithAddIf(T targetCollection, T resultCollection, Predicate<? super E> filter) {
Objects.requireNonNull(filter);
final Iterator<E> each = targetCollection.iterator();
while (each.hasNext()) {
E next = each.next();
if (filter.test(next)) {
resultCollection.add(next);
each.remove();
}
}
return resultCollection;
}
/**
* 移除集合中的多个元素并将结果存放到生成的新集合中后返回
* 此方法直接修改原集合
*
* @param <T> 集合类型
* @param <E> 集合元素类型
* @param targetCollection 被操作移除元素的集合
* @param filter 用于是否移除判断的过滤器
* @return 移除结果的集合
*/
@SuppressWarnings("unchecked")
public static <T extends Collection<E>, E> T removeWithAddIf(T targetCollection, Predicate<? super E> filter) {
Collection<E> resultCollection = new ArrayList<>();
removeWithAddIf(targetCollection, resultCollection, filter);
return (T) resultCollection;
}
/**
* 通过Editor抽取集合元素中的某些值返回为新列表<br>
* 例如提供的是一个Bean列表通过Editor接口实现获取某个字段值返回这个字段值组成的新列表

View File

@ -39,6 +39,23 @@ public class CollUtilTest {
Assert.assertFalse(CollUtil.contains(list, s -> s.startsWith("d")));
}
@Test
public void testRemoveWithAddIf() {
ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3);
ArrayList<Integer> exceptRemovedList = CollUtil.newArrayList(2, 3);
ArrayList<Integer> exceptResultList = CollUtil.newArrayList(1);
ArrayList<Integer> resultList = CollUtil.removeWithAddIf(list, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList);
Assert.assertEquals(resultList, exceptResultList);
list = CollUtil.newArrayList(1, 2, 3);
resultList = new ArrayList<>();
CollUtil.removeWithAddIf(list, resultList, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList);
Assert.assertEquals(resultList, exceptResultList);
}
@Test
public void testPadLeft() {
List<String> srcList = CollUtil.newArrayList();