一、背景
在日常寫代碼的過程中,針對List集合,統(tǒng)計里面的某個屬性,是經(jīng)常的事情,針對List的某個屬性的統(tǒng)計,我們目前大部分時候的代碼都是這樣寫,每統(tǒng)計一個變量,就要定義一個值,且要在for循環(huán)增加一行累計的代碼,比較繁瑣,而且代碼寫出來不夠優(yōu)雅。
Double chineseSum = 0d;
//班級積分
Double classScore = 0d;
//定義變量
// .....
for(Student student : students){
//統(tǒng)計語文成績
chineseSum += student.getChinese();
//統(tǒng)計班級成績
classScore += student.getClassScore();
//統(tǒng)計.....
}
二、解決思路
利用頂層抽象的思維,既然要做統(tǒng)計,可以抽象出幾個點
- 統(tǒng)計的屬性是什么?
- 如何統(tǒng)計?
- 統(tǒng)計之后的結(jié)果放到哪里?
基于這三個維度的最終核心思想:給定任意的集合,你告訴我要統(tǒng)計哪些屬性,如何統(tǒng)計,我把結(jié)果統(tǒng)計好放到你設(shè)定的對象里面。這樣有點像Spring的控制反轉(zhuǎn),調(diào)用方只要告訴我規(guī)則就好了,統(tǒng)計的執(zhí)行過程由統(tǒng)計組件進行幫你統(tǒng)計。調(diào)用方只需要調(diào)用過后拿結(jié)果就行了。
三、實現(xiàn)方案
基于上面所說的思想,再結(jié)合Java 1.8的函數(shù)式編程以及泛型和設(shè)計模式,實現(xiàn)了List集合的屬性統(tǒng)計組件
核心實現(xiàn)類圖
四、關(guān)鍵代碼展示
通過構(gòu)建統(tǒng)計上下文進行統(tǒng)計,通過函數(shù)式編程的方法指定統(tǒng)計屬性、統(tǒng)計規(guī)則、統(tǒng)計結(jié)果放到哪里
/**
* 統(tǒng)計年齡、統(tǒng)計分數(shù)
* @author chenfoxin
* @date: 2022/9/1 17:40
* @return AbstractConsolidationMode
* @param statResult
*/
public static StatContext<StatResult> buildStatStudentContext(StatResult statResult){
return new StatContext<>(
statResult,
//統(tǒng)計年齡
new StatAttribute<>(Student::getAge, new IntegerStatRule(), StatResult::setAge),
//統(tǒng)計分數(shù)
new StatAttribute<>(Student::getClassScore, new DoubleStatRule(NumberConstants.INT_TWO), StatResult::setScore),
//統(tǒng)計數(shù)學(xué)+語文成績(組合字段)
new StatAttribute<>((Function<Student, Double>) student -> DoubleUtils.add(NumberConstants.INT_TWO,
student.getChinese(),student.getMath()), new DoubleStatRule(NumberConstants.INT_TWO),
StatResult::setMathChinese));
}
List<Student> students = new ArrayList<>();
Student stu1 = new Student(11,98D,95D,87D);
Student stu2 = new Student(12,97D,56D,78D);
//構(gòu)建list
students.add(stu1);
students.add(stu2);
//創(chuàng)建全局對象
StatResult statResult = new StatResult();
//構(gòu)建統(tǒng)計上下文
StatContext<StatResult> context = StatManager.buildStatStudentContext(statResult);
//進行統(tǒng)計
StatManager.execute(students,context);
//輸出結(jié)果
log.info("統(tǒng)計結(jié)果:" + statResult);
感興趣的朋友可以到我的博客上把源碼拉取下來看看文章來源:http://www.zghlxwxcb.cn/news/detail-625038.html
基于JAVA 1.8函數(shù)式編程 泛型 設(shè)計模式抽象的通用 List統(tǒng)計組件: 設(shè)計模式、Java8新特性實戰(zhàn) - List<T> 抽象統(tǒng)計組件文章來源地址http://www.zghlxwxcb.cn/news/detail-625038.html
到了這里,關(guān)于設(shè)計模式、Java8新特性實戰(zhàn) - List<T> 抽象統(tǒng)計組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!