Merge pull request #2980 from youzipi/feat

feat: CollUtil add groupByFunc
This commit is contained in:
Golden Looly 2023-03-14 19:01:27 +08:00 committed by GitHub
commit f502342611
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 6 deletions

View File

@ -2023,8 +2023,12 @@ public class CollUtil {
* @return 分组列表
*/
public static <T> List<List<T>> groupByField(final Collection<T> collection, final String fieldName) {
return groupByFunc(collection, t -> BeanUtil.getFieldValue(t, fieldName));
}
public static <T,D> List<List<T>> groupByFunc(final Collection<T> collection, final Function<T,D> getter) {
return group(collection, new Hash32<T>() {
private final List<Object> fieldNameList = new ArrayList<>();
private final List<Object> hashValList = new ArrayList<>();
@Override
public int hash32(final T t) {
@ -2032,11 +2036,11 @@ public class CollUtil {
// 非Bean放在同一子分组中
return 0;
}
final Object value = FieldUtil.getFieldValue(t, fieldName);
final int hash = fieldNameList.indexOf(value);
final D value = getter.apply(t);
final int hash = hashValList.indexOf(value);
if (hash < 0) {
fieldNameList.add(value);
return fieldNameList.size() - 1;
hashValList.add(value);
return hashValList.size() - 1;
} else {
return hash;
}

View File

@ -427,6 +427,26 @@ public class CollUtilTest {
Assert.assertEquals("李四", groupByField.get(1).get(0).getName());
}
@Test
public void groupByFuncTest() {
final List<TestBean> list = ListUtil.of(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<List<TestBean>> groupByField = CollUtil.groupByFunc(list, TestBean::getAge);
Assert.assertEquals("张三", groupByField.get(0).get(0).getName());
Assert.assertEquals("王五", groupByField.get(0).get(1).getName());
Assert.assertEquals("李四", groupByField.get(1).get(0).getName());
}
@Test
public void groupByFunc2Test() {
final List<TestBean> list = ListUtil.of(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<List<TestBean>> groupByField = CollUtil.groupByFunc(list, a -> a.getAge() > 12);
Assert.assertEquals("张三", groupByField.get(0).get(0).getName());
Assert.assertEquals("王五", groupByField.get(0).get(1).getName());
Assert.assertEquals("李四", groupByField.get(1).get(0).getName());
}
@Test
public void sortByPropertyTest() {
final List<TestBean> list = ListUtil.of(
@ -854,7 +874,7 @@ public class CollUtilTest {
final List<Long> result = CollUtil.subtractToList(list1, list2);
Assert.assertEquals(1, result.size());
Assert.assertEquals(1L, (long)result.get(0));
Assert.assertEquals(1L, (long) result.get(0));
}
@Test