Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order 2 related arrays

I have 2 String[] Arrays.

the first is itemArray, it contains the names of products. the second is priceArray, it contains the prices for each item.

itemArray[0] relates to priceArray[0] itemArray[1] relates to priceArray[1]

I need to sort the arrays based on the price.

Using the following code will order the price array

List<Float> pricefloatArrayTo Order = new ArrayList<Float>();
for (String s : priceArray) {                        
                        pricefloatArrayTo (Float.valueOf(s));  

                    }

                    Collections.sort(pricefloatArrayTo );

Only problem is, the itemArray now needs ordering in accordance with the priceArray so that the arrays once again match up.

Can anone suggest a method that I can use to sort both arrays based on the priceArray. Thanks in advance

like image 233
brux Avatar asked Jan 24 '26 07:01

brux


2 Answers

How about instead of keeping the elements separated in two arrays, create a new class which contains both the Price and the Item. You can them make this class implement the Comparable interface which you can use to sort an array containing this new class by Price.

For example:

public class Item implements Comparable<Item> {
  public String name;
  public BigDecimal price;

  @Override
  public int compareTo( Item o ) {
    return price.compareTo( o.price );
  }
}

(I've removed the normal get/set encapsulation and null checks for clarity)

You can then have an array of this class(or a List) which you can then sort.

like image 132
agxs Avatar answered Jan 26 '26 21:01

agxs


I would suggest that you stop using two arrays - that instead you create a single array of type Item (or Product, or whatever) where an Item has a price (ideally BigDecimal rather than float) and a name (as a string). You can then sort the single array passing in a comparator which will compare items by price.

It's likely to make your code simpler in various places, not just here. Whenever you've got multiple collections which are meant to be kept in step like this, keeping different aspects of the same fundamental unit of data, it's worth trying to improve the encapsulation.

like image 41
Jon Skeet Avatar answered Jan 26 '26 21:01

Jon Skeet