Add the 5 largest values to an array


I have the following method:

public static void topFiveSales(int idEmpresa) {
    List < Entidade > allList = Entidade.findByEmpresa(idEmpresa);
    float totalVendasByEntidade;
    Float[] totais = new Float[5];

    for (Entidade ent: allList) {
        totalVendasByEntidade = entidade.valor;
        for (int i = 0; i < 5; i++) {
            if (totalVendasByEntidade > totais[i]) {
                totais[i] = totalVendasByEntidade;

What will be the best way for me to get the totalVendasByEntidade value and add it to a Array of 5 positions and whenever I get that value from each entity, compare with the 5 Array values and if it is greater than one of them, replace it with the smaller one?

asked by anonymous 30.07.2015 / 16:55

2 answers


Let's do in 3 steps what you need.

1st) Your entity needs to be compared to another entity so we can sort the list. For this, we will implement the Comparable interface and say that when comparing one Entity with the other, we will compare the value of entities. So:

public class Entidade implements Comparable<Entidade>{
   // codigo que ja tinha antes
   public int compareTo(Entidade outraEntidade){
        if (this.valor < outraEntidade.valor) {
            return -1;
        else if (this.valor > outraEntidade.valor) {
            return 1;
        else return 0;

2nd) To sort the vector using the functions of the Collections class, we need to create a "comparator" that compares one entity with another. We will do this we will implement the Comparator interface, according to the following code:

public class EntidadeComparator implements Comparator<Entidade> {
    public int compare(Entidade entidade, Entidade outraEntidade) {
        return Entidade.getValor().

3rd) Finally, your topFiveSales method will return the list with listTopFiveSales.

TIP: methods represent actions of our class. For better code consistency, I suggest changing the method name from topFiveSales to listTopFiveSales or getTopFiveSales

His code is simple:

  • Search the entire list (allList)
  • Sort the list incrementally
  • If size (list) is less than or equal to 5 elements, returns list
  • Otherwise, we get the last 5 elements and return
  • I also put the option to return the list increasing or decreasing

Follow the code:

public static List<Entidade> getTopFiveSales(int idEmpresa) {
        List < Entidade > allList = Entidade.findByEmpresa(idEmpresa);
        Collections.sort(allList, new EntidadeComparator());
        List<Entidade> listTopFive = null;
        if(allList.size() <= 5){
           listTopFive = allList;
          listTopFive = allList.sublist(allList.size()-5,allList.size());
        return listTopFive; //retorna a lista de forma crescente
        // return Collections.reverse(listTopFive); // retorna a lista de forma decrescente

Recapping what was done:

1) Our Entity implemented the Comparable interface by saying how one Entity will be compared to the other. 2) We created a Comparator that compares 2 entities. > 3) We implemented the method and used Collections.sort (array, Comparator) using the comparator we created.

I hope I have been useful.

Source: Caelum Blog

EDIT: method explanation sublist

According to the ArrayList documentation , the < subList(int fromIndex, int toIndex) returns a sublist of fromIndex inclusive up to toIndex exclusive .

In our method we use listTopFive = allList.sublist(allList.size()-5,allList.size()); Using an array of 7 positions as an example: [0,1,2,3,4,5,6] , we will get size-5 = 2 (inclusive) up to size (exclusive), or be: size-1 So we will get the elements [2,3,4,5,6] which are the last 5 of array .

20.08.2015 / 14:44

One way is to first sort the vector in descending order, and then get the first five elements of the vector.

// Declara um vetor temporário do mesmo tamanho que a lista.
Float[] temp = new Float[allList.size()];

// Adiciona todos os valores para o vetor temporário.
for(int i=0; i< allList.size(); i++) {
    temp[i] = allList[i].valor;

// Ordena o vetor em ordem decrescente
Float.sort(temp, (a, b) ->, a), false);

// Adiciona para o vetor de totais os cinco primeiros maiores valores
for (int i = 0; i < 5; i++) {
    totais[i] = temp[i];
30.07.2015 / 18:14