当前位置:网站首页>函數式接口,方法引用,Lambda實現的List集合排序小工具
函數式接口,方法引用,Lambda實現的List集合排序小工具
2022-07-04 16:12:00 【人形bug制造機9527】
1.在Java8中引入了一個函數式接口Consumer的對象,該對象可以把方法作為參數進行傳遞。
關於lambda的教程
/** * 集合排序 */
@AllArgsConstructor
public class CollSort {
// 排序因子
private final Long order;
public final static CollSort DESC = new CollSort(-1L);
public final static CollSort ASC = new CollSort(1L);
// 根據數字排序
public <E> Collection<E> sort(Collection<E> collection, ProcessorNumber<E> getParam) {
return collection.stream()
.filter(Objects::nonNull)
.sorted((o1, o2) -> {
// 這裏執行傳入的抽象方法,並傳入函數方法需要的參數,
// getParam的返回值已經在抽象函數方法中確定了
long result = Long.parseLong(String.valueOf(getParam.accept(o1))) - Long.parseLong(String.valueOf(getParam.accept(o2)));
result = result * order; // 排序系數介入
return result == 0 ? 0 : result < 0 ? -1 : 1;
})
.collect(Collectors.toList());
}
// 根據時間排序
public <E> Collection<E> sort(Collection<E> collection, ProcessorDate<E> getParam) {
return collection.stream()
.filter(Objects::nonNull) // 無效數據過濾
.sorted((o1, o2) -> {
long t1 = getParam.accept(o1).getTime(); // 這裏抽象方法getParam的返回值已經在抽象函數方法中確定了
long t2 = getParam.accept(o2).getTime();
long result = t1 - t2;
result = result * order; // 排序系數介入
return result == 0 ? 0 : result < 0 ? -1 : 1;
})
.collect(Collectors.toList());
}
}
@FunctionalInterface
interface ProcessorDate<E> {
/** * 獲取對象時間屬性的抽象函數方法 * * @param t 對象 * @return 對象的時間屬性 */
Date accept(E t);
}
@FunctionalInterface
interface ProcessorNumber<E> {
/** * 獲取對象數字屬性的抽象函數方法 * * @param t 對象 * @return 對象的數字屬性 */
Number accept(E t);
}
使用
public static void main(String[] args) {
SortTest sortTest = new SortTest();
ArrayList<User> users = new ArrayList<>();
users.add(new User("zz", 14,new Date()));
users.add(new User("zz", 17,new Date(System.currentTimeMillis()+1000000)));
users.add(new User("zz", 11,new Date(System.currentTimeMillis()+4000000)));
users.add(new User("zz", 15,new Date(System.currentTimeMillis()+9000000)));
users.add(new User("zz", 21,new Date(System.currentTimeMillis()+8000000)));
users.add(new User("zz", 7,new Date(System.currentTimeMillis()+3000000)));
sortTest.test(users);
}
public void test(List<User> users) {
// 就普通的工具方法調用,區別就是參數是一個方法,也可以直接引用方法
Collection<User> ageSort = CollSort.ASC.sort(users, User::getAge);
System.out.println("年齡排序=========================");
ageSort.forEach(System.out::println);
System.out.println("生日排序排序======================");
Collection<User> timeSort = CollSort.DESC.sort(users, User::getBirthDay);
timeSort.forEach(System.out::println);
}
效果
可以根據需求自行拓展函數接口,需要注意參數類型
和返回值類型
,大多數時候更換返回值類型就可以了;
參數類型以及返回值類型影響這個函數方法在調用的時候需要傳入的參數,以及響應值
边栏推荐
- Talking about Net core how to use efcore to inject multiple instances of a context annotation type for connecting to the master-slave database
- Penetration test --- database security: detailed explanation of SQL injection into database principle
- Weekly recruitment | senior DBA annual salary 49+, the more opportunities, the closer success!
- . Net delay queue
- 這幾年爆火的智能物聯網(AIoT),到底前景如何?
- 深入JS中几种数据类型的解构赋值细节
- Unity预制件Prefab Day04
- [Chongqing Guangdong education] National Open University spring 2019 1396 pharmaceutical administration and regulations (version) reference questions
- Selenium browser (2)
- LeetCode 58. Length of the last word
猜你喜欢
Functional interface, method reference, list collection sorting gadget implemented by lambda
2022年九大CIO趨勢和優先事項
LNX efficient search engine, fastdeploy reasoning deployment toolbox, AI frontier paper | showmeai information daily # 07.04
[North Asia data recovery] data recovery case of database data loss caused by HP DL380 server RAID disk failure
Common knowledge of unity Editor Extension
干货 | fMRI标准报告指南新鲜出炉啦,快来涨知识吧
每周招聘|高级DBA年薪49+,机会越多,成功越近!
Move, say goodbye to the past again
Dry goods | fMRI standard reporting guidelines are fresh, come and increase your knowledge
Model fusion -- stacking principle and Implementation
随机推荐
数据湖治理:优势、挑战和入门
How did the beyond concert 31 years ago get super clean and repaired?
[flask] ORM one to many relationship
Audio and video technology development weekly | 252
In today's highly integrated chips, most of them are CMOS devices
Unity脚本API—Component组件
The per capita savings of major cities in China have been released. Have you reached the standard?
怎么判断外盘期货平台正规,资金安全?
Usage of database functions "recommended collection"
Working group and domain analysis of Intranet
[Chongqing Guangdong education] National Open University spring 2019 1396 pharmaceutical administration and regulations (version) reference questions
Temperature control system based on max31865
JS tile data lookup leaf node
Laravel simply realizes Alibaba cloud storage + Baidu AI Cloud image review
Object distance measurement of stereo vision
LeetCode 1184. Distance between bus stops -- vector clockwise and counterclockwise
Move, say goodbye to the past again
LeetCode 1184. 公交站间的距离 ---vector顺逆时针
Unity预制件Prefab Day04
Unity动画Animation Day05