I have some array:
trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]
and I want to sort them by tickers
and then by dates
.
how can I sort them?
I have some array:
trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]
and I want to sort them by tickers
and then by dates
.
how can I sort them?
Seems like you should rethink the design. I think creating a class for these properties and having a collection of the class type is better:
class Trade
{
double price;
double volume;
Date date;
String tickers;
}
Then for sorting implement the Comparator
interface. An example, after you create the class could be: How to sort by two fields in Java?
Another option, as mentioned by saka1029, is to use Comparator's functions of Comparator.comparing
and Comparator.thenComparing
on the steam of the class's objects.
Define inner class Trade
like this.
int n = 10;
int[] trade_prices = new int[n];
int[] trade_volumes = new int[n];
Date[] trade_dates = new Date[n];
String[] trade_tickers = new String[n];
// fill data...
class Trade {
final int i;
Trade(int i) { this.i = i; }
int price() { return trade_prices[i]; }
int volume() { return trade_volumes[i]; }
Date date() { return trade_dates[i]; }
String ticker() { return trade_tickers[i]; }
}
Trade[] trades = IntStream.range(0, n)
.mapToObj(Trade::new)
.sorted(Comparator.comparing(Trade::ticker).thenComparing(Trade::date))
.toArray(Trade[]::new);
Then you can get sorted first price as trades[0].price()
.
Original arrays are not changed.
Make a class with constructors and methods in it and declare your arrays as global. You can write a function to sort your arrays.