Java – sort 2D arrays by 2D
•
Android
I need to classify the goods according to the price
The price of each item is stored in a JSON array
I created a two-dimensional array to store names and prices
Like this
String [][] priceArray = new String [itemArray.length()] [2];
for(int i = 0; i < itemArray.length(); i++)
{
//put the item name in the first dimension
priceArray[i][0] = itemArray.getJSONObject(i).getString("name");
//put the item price in the second dimension
priceArray[i][1] = itemArray.getJSONObject(i).getString("baseprice");
}
//DEBUG TO SEE THE RESULTS
for(int i = 0; i < priceArray.length; i++)
{
Log.i("Item name : Item Price", priceArray[i][0] + " : " + priceArray[i][1]);
}
This works... But how can I sort the array at the price of the second dimension?
Is this even the best way?
resolvent:
Better method: use OO programming. First, create a class item containing name and price:
class Item {
String name;
BigDecimal price;
public String toString() { return "ITEM: {name:" + name + ", price: " + price + "}" }
}
Then create a list of items instead of a 2D array:
List<Item> items = new ArrayList<Item>();
for(int i = 0; i < itemArray.length(); i++)
{
Item item = new Item();
item.name = itemArray.getJSONObject(i).getString("name");
item.price = new BigDecimal(itemArray.getJSONObject(i).getString("baseprice"));
items.add(item);
}
Finally, if you need, you can order by name:
// Sort by name
Collections.sort(items, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.name.compareTo(o2.name);
}
});
// at this point, items will be ordered by name
Or if you want to order at a price:
// Sort by price
Collections.sort(items, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.price.compareTo(o2.price);
}
});
// at this point, items will be ordered by price
Of course, I missed some small problems, such as using getters and setters instead of directly accessing item fields, but the purpose is to show this idea
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码