如何在运行时在java中向列表添加值

时间:2018-04-11 18:08:35

标签: java java-8

我正在尝试使我的代码灵活,但我不确定它是否可行。

我有以下对象:

        Vehicle v1 = new Vehicle();
        v1.setColor("red");
        v1.setPriority(Integer.valueOf(0));
        v1.setModel("sport");

        Vehicle v2 = new Vehicle();
        v2.setColor("blue");
        v2.setPriority(Integer.valueOf(0));
        v2.setModel("sedan");

        Vehicle v3 = new Vehicle();
        v3.setColor("red");
        v3.setPriority(Integer.valueOf(1));
        v3.setModel("sport");

        Vehicle v4 = new Vehicle();
        v4.setColor("blue");
        v4.setPriority(Integer.valueOf(1));
        v4.setModel("sedan");

        Vehicle v5 = new Vehicle();
        v5.setColor("black");
        v5.setPriority(Integer.valueOf(2));
        v5.setModel("hashback");

我希望过滤那些由n属性重复并考虑优先级的人。例如:

private static void checkVehicle2(List<Vehicle> current, List<Vehicle> previous)
    {
        Map<List<String>, Vehicle> map = new HashMap<>();
        List<Vehicle> flat = flatMap(current, previous); //joins current and previous
        List<Vehicle> sort = sortByPriority(flat); //descent order[3,2,1,0]

        for(int index = 0; index < sort.size(); index++)
        {
            List<String> key = new ArrayList<>();
            key.add(sort.get(index).getColor());
            key.add(sort.get(index).getModel());
            map.put(key, sort.get(index));
        }
    }

方法checkVehicle2执行我想要的操作(过滤器采用颜色,模型和优先级)。 的答案:  {[black, hashback]=Vehicle [color=black, model=hashback, year=null, priority=2], [red, sport]=Vehicle [color=red, model=sport, year=null, priority=0], [blue, sedan]=Vehicle [color=blue, model=sedan, year=null, priority=0]}

重点是不灵活。我想对房产数量(1,2等)持开放态度。你有什么想法吗?

0 个答案:

没有答案