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

I am relatively new to programming, and I would like you to help me sort these arrays. The idea is to display a menu item in textArea and sort the items by name. Parabolic arrays contain food, while others contain prices.

String[] items  = {"Gatspy", "Coffee", "Chicken", "Mango Juice"};
double[] prices = {8.99, 23.50, 29.90, 7.50};
+3
source share
3 answers

Do not use arrays in the first place, use Map. In your case, use TreeMap, 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>");
}

Link: Java Tutorial > Trail Collections > Map Interface

+3
source

, Comparator ? .

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() );
+3

You should use objects:

public class Item {
    private String name;
    private double price; // you shouldn't use doubles for money, but this is unrelated

    public Item(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return this.name;
    }

    public double getPrice() {
        return this.price;
    }
}

Then you can have an array (or list) of elements:

private Item[] items = new Item[] {new Item("Gtaspy", 8.99), ...};

and you can sort this array using Arrays.sort () (or Collections.sort () if you use a list instead of an array).

Read the Java collection tutorial for more information .

0
source

All Articles