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.
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. */
}
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);
Edit: 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());
};
Then, just give your comparators to the Array.sort()
method:
Arrays.sort(products, nameComparator);
/* or */
Arrays.sort(products, priceComparator);