Problem with using lists in Java

1

I have a file loaded with 300,000 thousand prices. I need to put the prices in ascending order in a list. If I put it in standard mode, analyzing linearly where to enter each price, my algorithm gets very slow. Does anyone have an idea of a quick way to do this?

EDIT:

These are random prices that I need to sort.

19.5, 11.3, 17.43, 1.32, 36.45, etc.

I'm doing a contextualization because what I really want to do is a bit different but requires knowledge of my system. This is an abstraction.

EDIT. 2:

if (Type == 0) {
            for (int i = 0; i < Objeto.size(); i++) {
                //Ordena pelo menor preço. Se o primeiro elemento tiver preço menor que algum da lista completa,
                //tal elemento é inserido anterior a esse algum
                if (PrimeiroElemento.getPrice() > Objeto.get(i).getPrice()) {
                    return i;
                }
                if (PrimeiroElemento.getPrice() == Objeto.get(i).getPrice()) {
                    //se os preços forem iguais, ordena pelo tempo
                    if (PrimeiroElemento.getTimestamp() < Objeto.get(i).getTimestamp()) {
                        return i;
                    }
                }
            }
    
asked by anonymous 05.06.2017 / 22:06

1 answer

0

You can work with ConcurrentSkipListSet , it works equal to Set but it is appropriate to work in multithreads and also more secure with respect to data order,

// Define a ordem
Comparator sort = Collections.reverseOrder();
// Cria a collection
Collection<Double> precos = new ConcurrentSkipListSet<>(sort);

// Teste crio um pool com 100 threads onde cada thread adiciona dentro
// da lista um valor aleatório
ExecutorService pool = Executors.newFixedThreadPool(100);
for (int i = 0; i < 300000; i++) {
    pool.submit(() -> {
        precos.add(Math.random());
    });

}

// Finaliza o pool
pool.shutdown();
System.out.println("Done!");

// Exibe o top 10
int index = 1;
for (double p : precos) {
    System.out.println(p);
    if (index++ == 10) {
        break;
    }
}

See that at the end of the process the price collection has all the data that the threads added in a random order.

The order by default is increasing (constructor empty) plus you can put it in descending order or customize its comparator by passing in the ConcurrentSkipListSet constructor, eg:

Comparator sort = new Comparator<Double>() {
    @Override
    public int compare(Double o1, Double o2) {
        return Double.compare(o1, o2);
    }
};

In this case you just have to adapt the comparator to work according to the specifications of the EDIT. 2: of your code

    
05.06.2017 / 22:54