Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to sort two parallel arrays, one is of String and the other of double data types

Tags:

java

arrays

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};
like image 785
TaIra Avatar asked May 24 '11 10:05

TaIra


2 Answers

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() );
like image 108
Liv Avatar answered Oct 12 '22 09:10

Liv


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

like image 31
Sean Patrick Floyd Avatar answered Oct 12 '22 08:10

Sean Patrick Floyd