package com.test.util;import java.util.Collection;import org.apache.commons.collections.CollectionUtils;/** * 自定义集合处理类 */public class CollectionsCustom { /** * 将传入的collection内对象进行计算后得出结果 * @param original 计算前collection * @param reduceFunction 计算方式 * @param initValue 计算结果初始值 * @param <Input> collection对象类型 * @param <Output> 结果类型 * @return */ public static <Input, Output> Output reduce(Collection<Input> original, Output initValue, ReduceFunction<Input, Output> reduceFunction) { Output result = initValue; if (CollectionUtils.isEmpty(original)) { return result; } if (reduceFunction == null) { return result; } for (Input input : original) { result = reduceFunction.apply(input, result); } return result; } /** * 自定义计算接口 * @param <Input> * @param <Result> */ public interface ReduceFunction<Input, Result> { Result apply(Input input, Result lastResult); }}
package com.test;import java.math.BigDecimal;import java.util.Arrays;import java.util.List;import com.test.util.CollectionsCustom;public class TestCollection { private static List<User> list = Arrays.asList( new User("张三", BigDecimal.valueOf(35.6), 18), new User("李四", BigDecimal.valueOf(85), 30), new User("赵六", BigDecimal.valueOf(66.55), 25)); public static void main(String[] args) { //统计集合内分数之和 testTotalScore(); //统计集合内年龄之和 testTotalAge(); } private static void testTotalScore(){ //统计集合内分数之和 BigDecimal totalScore = CollectionsCustom.reduce(list, BigDecimal.ZERO, new CollectionsCustom.ReduceFunction<User, BigDecimal>() { @Override public BigDecimal apply(User input, BigDecimal lastResult) { // TODO Auto-generated method stub return lastResult.add(input.getScore()); } }); System.out.println("总共分数:" + totalScore); } private static void testTotalAge(){ //统计集合内年龄之和 Integer totalAge = CollectionsCustom.reduce(list, 0, new CollectionsCustom.ReduceFunction<User, Integer>() { @Override public Integer apply(User input, Integer lastResult) { // TODO Auto-generated method stub return lastResult += input.getAge(); } }); System.out.println("总共年龄:" + totalAge); } static class User{ private String userName; //姓名 private BigDecimal score;//分数 private Integer age; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public BigDecimal getScore() { return score; } public void setScore(BigDecimal score) { this.score = score; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(String userName, BigDecimal score, Integer age) { super(); this.userName = userName; this.score = score; this.age = age; } public User() { // TODO Auto-generated constructor stub } }}