java - 按升序对包含多个元素的数组进行排序
问题描述
我也在寻找可以合并 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)
};
}
如何按类型按升序对该数组进行排序?而且还按价格?
我研究过使用比较器,但它们似乎不符合我的目标。我也不确定,因为价格是双倍的。
解决方案
您可以使用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.comparingInt
Java 8 中添加的更简洁的功能。参考 KaNa0011 的回答
检查对象排序以获得更清晰的信息。
推荐阅读
- python - 类型错误:索引()缺少 1 个必需的位置参数:'subject_slug'
- javascript - 如何为 firebase 功能选择不同的数据库?
- reactjs - 如何纠正打字稿错误?(道具类型库)
- python - 使用 html 编译 jinja 2 时出错
- algorithm - 多个依赖的自动完成
- java - 服务器和客户端之间的套接字对象不同
- angular - 来自错误验证的 Angular 11 反应性不起作用
- c++ - 没有 void_t 的 SFINAE(可能是模板专业化问题)
- python - BeautifulSoup 不采用完整的 HTML 代码
- c++ - 将音频流写入循环缓冲区但分段错误读取值