mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
Merge pull request #1986 from scruel/dev-coll
✨ add removeWithAddIf methods
This commit is contained in:
commit
6cb86ce509
@ -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接口实现获取某个字段值,返回这个字段值组成的新列表
|
||||
|
@ -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();
|
||||
|
Loading…
x
Reference in New Issue
Block a user