阶梯配置
[
{
"grade": 1,
"max": 10,
"min": 0,
"price":0.5
},
{
"grade": 2,
"max": 50,
"min": 10,
"price":0.8
},
{
"grade": 3,
"max": 100,
"min": 50,
"price":1
},
{
"grade": 4,
"max": 200,
"min": 100,
"price":1.5
}
]
阶梯费用计算代码
java
public class DFTest {
/**
* 价格的上限值
*/
private static double topPrice=5;
/**
* 电费阶梯计价
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
/*计算最终的总金额*/
Double amount = 0.0;
/* 费用的点数*/
double dushu = 300;
/* 从配置文件中读取阶梯配置 并按照顺序进行排序*/
String string = FileUtils.readFileToString(new File("D:\\dev\\ideastore\\big_projects\\flink-cdc-demo\\data.json"),"utf-8");
List<GradeConfig> list = JSON.parseArray(string, GradeConfig.class);
List<GradeConfig> gradeConfigs = list.stream().sorted((o1, o2) -> o1.getGrade() - o2.getGrade()).collect(Collectors.toList());
/* 计算 费用总额*/
for (int i = 0; i <= gradeConfigs.size() - 1; i++) {
GradeConfig gradeConfig = gradeConfigs.get(i);
if ( dushu>gradeConfig.getMin() && dushu<=gradeConfig.getMax()){
// 在这个区间
// 直接 计算 之前的 所有分区的金额
Double aDouble = gradeConfigs.stream().filter(x -> x.getGrade() < gradeConfig.getGrade()).map(x -> {
double v = (x.getMax() - x.getMin()) * x.getPrice();
return v;
}).reduce((x, y) -> x + y).get();
amount += aDouble;
amount += (dushu - gradeConfig.getMin()) * gradeConfig.getPrice();
break;
}else if (i==gradeConfigs.size()-1){
// 找到最后一个了还不是则需计算全部区间的金额
Double aDouble = gradeConfigs.stream().map(x -> {
double v = (x.getMax() - x.getMin()) * x.getPrice();
return v;
}).reduce((x, y) -> x + y).get();
amount += aDouble;
amount += (dushu- gradeConfig.getMax())*topPrice;
}else{
// 还没有找完 继续找
}
}
System.out.println("总金额是:"+amount+"元");
}
}