I'm relatively new to the programming scene and i would like you to assist me with sorting of these arrays. The idea is to display a menu item on a textArea and sort the items by name. The parralel arrays contain food items and the other one prices.
String[] items = {"Gatspy", "Coffee", "Chicken", "Mango Juice"};
double[] prices = {8.99, 23.50, 29.90, 7.50};
Or how about encapsulating the item name and price in a class, then have a single array of instances of this class and use a Comparator
to sort them?
E.g.
public class Item {
private String name;
private double price;
...
//getters and setters for name and price
}
...
Item []items = { new Item("Gatspy", 8.99), .... };
...
class ItemComparator implements Comparator {
public int compare( Object o1, Object o2 ) {
Item i1 = (Item)o1;
Item i2 = (Item)o2;
return i1.getName().compareTo(i2.getName());
}
}
...
Arrays.sort( items, new ItemComparator() );
Don't use arrays in the first place, use a Map
. In your case, use a TreeMap
, it's sorted by its keys.
Map<String, Double> map = new TreeMap<String, Double>();
map.put("Gatspy", 8.99);
// put the other items
Now iterate over the entries:
for(Map.Entry<String, Double> entry : map.entrySet()){
System.out.println("<option value=\""
+ entry.getValue()
+ "\">"
+ entry.getKey()
+ "</option>");
}
Reference: Java Tutorial > Collections Trail > The Map Interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With