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
@Override
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().
compareTo(outraEntidade.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;
}
else{
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
.