说明:Java 两个 List中Map的id属性相同时,将两个map中的value属性相除。
List中嵌套Map,Map当中的属性有id,name,value。
List中为对象:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args){
List<Energy> beforeList = new ArrayList<>();
beforeList.add(new Energy(1, "张三去年家用电", 183));
beforeList.add(new Energy(2, "李四去年家用电", 276));
beforeList.add(new Energy(3, "王五去年家用电", 105));
List<Energy> thisList = new ArrayList<>();
thisList.add(new Energy(1, "张三今年家用电", 241));
thisList.add(new Energy(2, "李四今年家用电", 205));
thisList.add(new Energy(3, "王五今年家用电", 87));
for (Energy energy : thisList) {
if (energy!=null) {
Double dr = Double.valueOf(0);
Double thisValue = Double.valueOf(energy.getValue());
List<Energy> list= beforeList.stream()
.filter(objectMap -> objectMap.getId().equals(energy.getId()))
.collect(Collectors.toList());
if(list!=null && list.size()>0){
if(list.get(0)!=null && list.get(0).getId()!=null && Double.valueOf(String.valueOf(list.get(0).getValue()))!=0){
Double beforeValue = Double.valueOf(String.valueOf(list.get(0).getValue()));
dr = (beforeValue- thisValue)/beforeValue;
}
}
Double conservationRate = BigDecimal.valueOf(dr).multiply(new BigDecimal(100))
.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
System.out.println("节能率=(去年-今年)/去年*100%:" + conservationRate);
}
}
}
}
class Energy{
//id
private Integer id;
//名称
private String name;
private Integer value;
public Energy(){
}
public Energy(Integer id, String name, Integer value) {
this.id = id;
this.name = name;
this.value = value;
}
public void setId(Integer id){
this.id = id;
}
public Integer getId(){
return id;
}
public void setName(String name){
this.name= name;
}
public String getName(){
return name;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
List中为Map:
for (Map<String, Object> map : beforeList) {
if (!map.isEmpty()) {
Double dr = Double.valueOf(0);
Double thisValue = Double.valueOf(String.valueOf(map.get("value")));
List<Map<String, Object>> list= thisList.stream()
.filter(objectMap -> Integer.parseInt(String.valueOf(objectMap.get("id"))) == Integer.parseInt(String.valueOf(map.get("id"))))
.collect(Collectors.toList());
if(list!=null && list.size()>0){
if(list.get(0)!=null && list.get(0).get("id")!=null && Double.valueOf(String.valueOf(list.get(0).get("value")))!=0){
Double lastValue = Double.valueOf(String.valueOf(list.get(0).get("value")));
dr = (lastValue- thisValue)/lastValue;
}
}
Double rate = BigDecimal.valueOf(dr).multiply(new BigDecimal(100))
.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
System.out.println("节能率=(去年-今年)/去年*100%:" + rate);
map.put("rate",rate);
}
}
欢迎大神指正,欢迎更优写法!