首页 > 解决方案 > 按升序对包含多个元素的数组进行排序

问题描述

我也在寻找可以合并 for 循环的潜在方法。

我正在自己学习Java,并且对如何按类型和价格对以下数组进行排序感到非常困惑。这个问题与之前发布的问题不同,因为标记的问题仅涉及字符串,而我的使用整数、字符串和双精度数的组合。在发布自己的帖子之前,我在 Overflow 上查看的所有过去帖子都没有以任何方式涉及双打。

这就是我将 Item 定义为的内容。

public Item(int type, String name, double quantity, double price) {
        this.type = type;
        this.name = name;
        this.quantity = quantity;
        this.price = price;
    }

这是我的数组:

public static void main ()
    {Item [] shoppingItems = {new Item(2,"Cherry",9,1.35),
                    new Item(3,"Orange Juice",4,5.29),
                    new Item(5,"Hand Soap",2,1.77),
                    new Item(6,"Tooth Brush",3,4.55),
                    new Item(4,"Cupcake",3,2.95),
                    new Item(1,"Red Tomato Sauce",5.5,2.35),
                    new Item(3,"Chicken",1.9,2.48),
                    new Item(3,"Apple Pie",2,3.99),
                    new Item(7,"Bug Spray",1,9.28),
                    new Item(3,"Roast Beef",2.82,5.99),
                    new Item(5,"Light Bulb",3,3.92),
                    new Item(4,"Cookies",0.2,2.96),
                    new Item(2,"Watermelon",1.8,2.29)
                };
            }

如何按类型按升序对该数组进行排序?而且还按价格?

我研究过使用比较器,但它们似乎不符合我的目标。我也不确定,因为价格是双倍的。

标签: javaarrayssorting

解决方案


您可以使用Collections.sort方法来执行此操作。只需要传递一个自定义Comparator实现,如下所示。

    List<Item> list = Arrays.asList(shoppingItems);
    Collections.sort(list, new Comparator<Item>() {
        @Override
        public int compare(Item item1, Item item2) {
            int typeCompareResult = Integer.compare(item1.type, item2.type);
            if (typeCompareResult != 0) {
                return typeCompareResult;
            } else {
                return Double.compare(item1.price, item2.price);
            }
        }
    });

编辑:这是老派的做事方式。一开始这很好,但最终要利用Comparator.comparingIntJava 8 中添加的更简洁的功能。参考 KaNa0011 的回答

检查对象排序以获得更清晰的信息。


推荐阅读