mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
add ArrayUtil.distict
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user