通过内部数组的字段之一对多维数组进行排序 [英] Sort a multidimensional array by one of the fields of the inner array
问题描述
如何按内部数组的字段之一对多维数组排序?
How do I sort a multidimensional array by one of the fields of the inner array?
在Java中,如何创建这样的多维数组?以及如何按X字段对其进行排序?有例子吗?
In Java, How I can create a multidimensional array like this? and how I can sort it by X field? Any examples?
Array
(
[0] => Array
(
[name] => Sony TV
[price] => 600.00
)
[1] => Array
(
[name] => LG TV
[price] => 350.00
)
[2] => Array
(
[name] => Samsung TV
[price] => 425.00
)
}
推荐答案
您拥有的东西根本看起来并不像多维数组(嗯,它看起来像PHP多维数组,而不是Java多维数组),而是对象数组,其中每个对象都有一个名称"和一个价格"字段.
What you have doesn't look like a multidimensional array at all (well, it looks like a PHP multidimensional array, but not a Java one), but rather an array of objects, where each object has a "name" and a "price" field.
在这种情况下,您应该首先创建对象的类.我们称之为Product
:
In these case you should first create your object's class. Let's call it Product
:
public class Product implements Comparable<Product> {
private String name;
private BigDecimal price;
public Product(final String name, final BigDecimal price) {
this.name = name;
this.price = price;
}
@Override
public int compareTo(final Product other) {
return name.compareTo(other.name);
}
/* Other methods. */
/* Getters and setters for price and name. */
}
您会注意到该类实现了 compareTo
.这意味着可以订购产品的集合.然后,将Product
放入数组中,并使用Arrays.sort()方法对其进行排序:
You'll notice that this class implements Comparable<Product>
and has a method compareTo
. This means that a collection of products can be ordered. Then, you put your Product
s into an array and you use the Arrays.sort() method to sort it:
Product[] products = new Product[3];
products[0] = new Product("Sony TV", new BigDecimal("600.00"));
products[1] = new Product("LG TV", new BigDecimal("350.00"));
products[2] = new Product("Samsung TV", new BigDecimal("425.00"));
Arrays.sort(products);
编辑:我错过了您想要按任何字段进行排序的事实.在这种情况下,您需要比较器.每个字段需要一个:
I missed the fact that you wanted to sort by any field. In this case, you need Comparators. You'll need one per field:
Comparator<Product> nameComparator = new Comparator<Product>() {
@Override
int compare(final Product p1, final Product p2) {
return p1.getName().compareTo(p2.getName());
};
Comparator<Product> priceComparator = new Comparator<Product>() {
@Override
int compare(final Product p1, final Product p2) {
return p1.getPrice().compareTo(p2.getPrice());
};
然后,只需将您的比较器提供给Array.sort()
方法:
Then, just give your comparators to the Array.sort()
method:
Arrays.sort(products, nameComparator);
/* or */
Arrays.sort(products, priceComparator);
这篇关于通过内部数组的字段之一对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!