add method

This commit is contained in:
Looly
2022-04-17 08:53:43 +08:00
parent a8a866f35e
commit 7e36d0f076
7 changed files with 128 additions and 4 deletions

View File

@@ -878,6 +878,36 @@ public class CollUtilTest {
Assert.assertEquals(people.get(1).getGender(), "小孩");
}
@Test
public void distinctTest(){
final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.of(5, 3, 10, 9, 0, 5, 10, 9));
Assert.assertEquals(ListUtil.of(5, 3, 10, 9, 0), distinct);
}
@Test
public void distinctByFunctionTest(){
List<Person> people = Arrays.asList(
new Person("aa", 12, "man", 1),
new Person("bb", 13, "woman", 2),
new Person("cc", 14, "man", 3),
new Person("dd", 15, "woman", 4),
new Person("ee", 16, "woman", 5),
new Person("ff", 17, "man", 6)
);
// 覆盖模式下ff覆盖了aaee覆盖了bb
List<Person> distinct = CollUtil.distinct(people, Person::getGender, true);
Assert.assertEquals(2, distinct.size());
Assert.assertEquals("ff", distinct.get(0).getName());
Assert.assertEquals("ee", distinct.get(1).getName());
// 非覆盖模式下保留了最早加入的aa和bb
distinct = CollUtil.distinct(people, Person::getGender, false);
Assert.assertEquals(2, distinct.size());
Assert.assertEquals("aa", distinct.get(0).getName());
Assert.assertEquals("bb", distinct.get(1).getName());
}
@Data
@AllArgsConstructor
static class Person {

View File

@@ -285,6 +285,19 @@ public class ArrayUtilTest {
Assert.assertArrayEquals(new String[]{"aa", "bb", "cc", "dd"}, distinct);
}
@Test
public void distinctByFunctionTest() {
String[] array = {"aa", "Aa", "BB", "bb"};
// 覆盖模式下,保留最后加入的两个元素
String[] distinct = ArrayUtil.distinct(array, String::toLowerCase, true);
Assert.assertArrayEquals(new String[]{"Aa", "bb"}, distinct);
// 忽略模式下,保留最早加入的两个元素
distinct = ArrayUtil.distinct(array, String::toLowerCase, false);
Assert.assertArrayEquals(new String[]{"aa", "BB"}, distinct);
}
@Test
public void toStingTest() {
int[] a = {1, 3, 56, 6, 7};