0

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?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Mohammad_Hosein
  • 101
  • 1
  • 10
  • it can be done by for loops. but: 1- I don't know how (exactly) and 2- I don't know if it's the best way. – Mohammad_Hosein Jun 04 '17 at 05:29
  • maybe it can be done by 2 for loops one after another. instead of two loops inside each other. I mean one time I can sort them by dates and other time by tickers – Mohammad_Hosein Jun 04 '17 at 05:31

3 Answers3

8

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.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
3

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.

  • 1
    The use of `Comparator.comparing` is nice but the class's implementation for accessing external arrays without checking the indexes and nulls is a very bad practice IMO – Gilad Green Jun 04 '17 at 09:20
0

Make a class with constructors and methods in it and declare your arrays as global. You can write a function to sort your arrays.