java 以年度分組計算增長率 案例
阿新 • • 發佈:2020-08-01
計算年度增長率:
增長率公式: (a-b)b*100+'%' =》(前面的數字-後面的數字)/後面的數字*100
package cn.demo;
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author Administrator
* @date 2020/7/31
*/
public class GrowthRateDemo {
/**
* 初始化資料
* @return
*/
public static List<PersonInfo> getPerson(){List<PersonInfo> list=new ArrayList<>();
PersonInfo personInfo=new PersonInfo();
personInfo.setCountNumber(100);
personInfo.setCreateTime("2016");
PersonInfo personInfo2=new PersonInfo();
personInfo2.setCountNumber(450);
personInfo2.setCreateTime("2017");
PersonInfo personInfo4=new PersonInfo();
personInfo4.setCountNumber(22);
personInfo4.setCreateTime("2018");
PersonInfo personInfo5=new PersonInfo();
personInfo5.setCountNumber(100);
personInfo5.setCreateTime("2019");
PersonInfo personInfo6=new PersonInfo();personInfo6.setCountNumber(200);
personInfo6.setCreateTime("2020");
list.add(personInfo);
list.add(personInfo2);
list.add(personInfo4);
list.add(personInfo5);
list.add(personInfo6);
return list;
}
/**
* 計算年度增長率
* <p>
* 以年度分組
* <p>
* 增長率: (a-b)b*100+'%' =》(前面的數字-後面的數字)/後面的數字*100
*/
public static List<PersonInfo> getAnalysisData(){
List<PersonInfo> result =new ArrayList<>();
List<PersonInfo> person2 =new ArrayList<>();
List<PersonInfo> person0=new ArrayList<>();
List<PersonInfo> person = getPerson();
//第1項
PersonInfo personInfo0 = person.get(0);
personInfo0.setGrowthRate("0%");
person0.add(personInfo0);
//第一項不做比較
if (CollectionUtils.isNotEmpty(person)){
for (int i = 1; i < person.size(); i++) {
PersonInfo personInfo=new PersonInfo();
Integer countNumber = person.get(i).getCountNumber();
Integer countNumber1 = person.get(i - 1).getCountNumber();
if (countNumber<countNumber1){
//如果下個數大於上個數,則增長率 為 正
String growthRate=(countNumber1-countNumber)/countNumber*100+"%";
personInfo.setGrowthRate(growthRate);
}else if (countNumber>countNumber1){
//如果下個數小於上個數,則增長率 為 負
String growthRate= (countNumber-countNumber1)/countNumber1*100+"%";
personInfo.setGrowthRate("-"+growthRate);
}else{
//如果相等,增長率為 0
personInfo.setGrowthRate("0%");
}
personInfo.setCountNumber(person.get(i).getCountNumber());
personInfo.setCreateTime(person.get(i).getCreateTime());
person2.add(personInfo);
}
}
//list合併
result.addAll(person0);
result.addAll(person2);
return result;
}
public static void main(String[] args) {
List<PersonInfo> analysisData = getAnalysisData();
if (CollectionUtils.isNotEmpty(analysisData)){
analysisData.stream().forEach(item->{
System.out.println("數量:"+item.getCountNumber());
System.out.println("增長率:"+item.getGrowthRate());
System.out.println("時間:"+item.getCreateTime());
System.out.println("*****************************************************");
});
}
}
}