mirror of
https://gitee.com/dromara/hutool.git
synced 2025-08-20 00:44:27 +08:00
Pre Merge pull request !1371 from binyong/v5-dev
This commit is contained in:
commit
c993476686
@ -2,6 +2,7 @@ package cn.hutool.core.collection;
|
||||
|
||||
import cn.hutool.core.comparator.PinyinComparator;
|
||||
import cn.hutool.core.comparator.PropertyComparator;
|
||||
import cn.hutool.core.comparator.ReverseComparator;
|
||||
import cn.hutool.core.exceptions.ValidateException;
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.lang.Matcher;
|
||||
@ -326,6 +327,27 @@ public class ListUtil {
|
||||
return sort(list, new PropertyComparator<>(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Bean的多个属性排序并支持对不同属性单独设置升序或降序
|
||||
*
|
||||
* @param <T> 元素类型
|
||||
* @param list List
|
||||
* @param properties 指定多个排序属性
|
||||
* @param sorts 指定多个排序方式,如果sorts[i]为空则默认按升序排列,排序方式: desc:降序, asc:升序。默认升序
|
||||
* @return 排序后的List
|
||||
* @since 5.8.40
|
||||
*/
|
||||
public static <T> List<T> sortByProperties(List<T> list, String[] properties, String[] sorts) {
|
||||
for (int i = properties.length - 1; i >= 0; i--) {
|
||||
if (sorts != null && sorts.length > i && sorts[i].equals("desc")) {
|
||||
sort(list, new ReverseComparator<>(new PropertyComparator<>(properties[i], false,true)));
|
||||
}else{
|
||||
sort(list, new PropertyComparator<>(properties[i],false,true));
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据汉字的拼音顺序排序
|
||||
*
|
||||
|
@ -46,6 +46,17 @@ public class PropertyComparatorTest {
|
||||
assertEquals("a", sortedList.get(2).getB());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sortByPropertiesTest() {
|
||||
final List<User> users = ListUtil.toList(
|
||||
new User("1", "d"),
|
||||
new User("1", "a"),
|
||||
new User("3", "a"),
|
||||
new User("5", "c")
|
||||
);
|
||||
System.out.println(ListUtil.sortByProperties(users,new String[]{"a","b"},new String[]{"asc","desc"}));
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
static class User{
|
||||
|
Loading…
Reference in New Issue
Block a user