情景:

统计花费,并降序排列

1 数据:(前提:先按name 排好序),我直接把数据放到List集合中

 name     cost           month

 包子店    100.5           8

 包子店    200.5           9

  粉店       210.5           7

  粉店       300.5           8

  粉店       100.5           9

  超市      250.5            8

  超市      150.5            9

 

2.代码处理

1.实体类

 

public class Test implements Comparable<Test>{
    private String name;    //店铺名称
    private Double cost;    //花费金额
    private int month;      //月份,其实没啥用,主要是名称和花费金额

    public Test() { }

    public Test(String name, Double cost, int month) {
        this.name = name;
        this.cost = cost;
        this.month = month;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getCost() {
        return cost;
    }
    public void setCost(Double cost) {
        this.cost = cost;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month) {
        this.month = month;
    }

    @Override
    public String toString() {
        return "Test{" +
                "name='" + name + '\'' +
                ", cost=" + cost +
                ", month=" + month +
                '}';
    }

    //降序
    @Override
    public int compareTo(Test obj) {
        return obj.getCost().compareTo(this.getCost());// 如果要升序排列改为     this.getCost().compareTo(obj.getCost());
    }
}

2.方法

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestList {

    public static void Descending(){
        List<Test> list = new ArrayList<>();
        list.add(new Test("包子店",100.5,8));
        list.add(new Test("包子店",200.5,9));
        list.add(new Test("粉店",210.5,7));
        list.add(new Test("粉店",300.5,8));
        list.add(new Test("粉店",100.5,9));
        list.add(new Test("超市",250.5,8));
        list.add(new Test("超市",150.5,9));

        for(int i=0;i<list.size();i++){
            Test test = list.get(i);
            for (int j=i+1;j<list.size();j++){
                Test nextTest = list.get(j);
                if(test.getName().equals(nextTest.getName())){
                    //如果第一个店铺名和第二个店铺名相同,那么花费相加,然后删除第二个店铺,list大小变小,j索引应该后退一位
                    test.setCost(test.getCost()+nextTest.getCost());
                    list.remove(j);
                    j--;
                }
            }
        }
        Collections.sort(list);//降序排列
        for(Test test:list){
            System.out.println(test.toString());
        }
    }

    public static void main(String[] args) {
        Descending();
    }
}

3.结果

Test{name='粉店', cost=611.5, month=7}
Test{name='超市', cost=401.0, month=8}
Test{name='包子店', cost=301.0, month=8}

 

posted on 2020-09-25 09:44  regretDeeply  阅读(573)  评论(0)    收藏  举报