mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
add ArrayUtil.distict
This commit is contained in:
parent
870e22de00
commit
5e4718c8ce
@ -9,6 +9,7 @@
|
||||
* 【core】 CollUtil增加filterNew等方法(原filter变更为filterNew,新增filter)
|
||||
* 【crypto】 Sign增加setParameter方法
|
||||
* 【extra】 Sftp得put方法增加进度支持(issue#518@Github)
|
||||
* 【core】 ArrayUtil增加distinct方法
|
||||
|
||||
### Bug修复
|
||||
|
||||
|
@ -6,7 +6,9 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.collection.IterUtil;
|
||||
@ -3827,4 +3829,24 @@ public class ArrayUtil {
|
||||
public static boolean isAllNotEmpty(Object... args) {
|
||||
return false == hasEmpty(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去重数组中的元素,去重后生成新的数组,原数组不变<br>
|
||||
* 此方法通过{@link LinkedHashSet} 去重
|
||||
*
|
||||
* @param array 数组
|
||||
* @return 去重后的数组
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T[] distinct(T[] array) {
|
||||
if(isEmpty(array)) {
|
||||
return array;
|
||||
}
|
||||
|
||||
final Set<T> set = new LinkedHashSet<>(array.length, 1);
|
||||
for (T t : array) {
|
||||
set.add(t);
|
||||
}
|
||||
return toArray(set, (Class<T>)getComponentType(array));
|
||||
}
|
||||
}
|
||||
|
@ -225,4 +225,11 @@ public class ArrayUtilTest {
|
||||
arrayType = ArrayUtil.getArrayType(String.class);
|
||||
Assert.assertEquals(String[].class, arrayType);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void distinctTest() {
|
||||
String[] array = {"aa", "bb", "cc", "dd", "bb", "dd"};
|
||||
String[] distinct = ArrayUtil.distinct(array);
|
||||
Assert.assertArrayEquals(new String[] {"aa", "bb", "cc", "dd"}, distinct);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user