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> pricefloatArrayT开发者_开发问答o 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
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.
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.
If you really have to use 2 separate arrays, I'd suggest building a sorted map price -> array index and then take the ordered indices to sort the arrays.
Something like this:
//NOTE: this assumes both arrays have the same number of entries
float[] prices = ...;//assuming your price array
String[] itemNames = ... ;//assuming your item name array
TreeMap<BigDecimal, Integer> priceIndexMap = ...;//already sorted upon insertion
for( int i = 0; i < prices.length; i++ ) {
priceIndexMap.put(new BigDecimal(prices[i]), new Integer(i));
}
float[] pricesSorted = new float[prices.length];
String[] itemNamesSorted = new String[itemNames .length];
int newIndex = 0;
for( Integer index : priceIndexMap.values() ) {
pricesSorted[newIndex] = prices[index];
itemNamesSorted [newIndex] = itemNames [index];
newIndex++;
}
Again, I'd like to point out that this approach is not recommended, as the others already said. Only use it if you really have to.
精彩评论