Reputation: 707
I have a list of objects List<FileNameAndScoreDTO> fileNameAndScoreList = new ArrayList<>();
I want to access the top 7 names of files on the basis of scores.
FileNameAndScoreDTO.java
public class FileNameAndScoreDTO {
String file_name;
int score;
long category;
}
whereas the category could be breakfast,lunch or dinner. I want a total of 21 file names on the basis of highest scores in which 7 file names of breakfast,7 of lunch and 7 of dinner.
Please help me to resolve this.
Upvotes: 0
Views: 66
Reputation: 1457
First of all i'd recommend to use a String
for the category or even better an Enum
.
I assumed you want it in descending order to get the seven file names with the highest score.
The method below filters for the given category, sorts the leftover objects by the score in descending order, limits the amount of objects to 7 and returns their filenames as List<String>
public List<String> getTopSevenNamesOrderedByScoreDescOfCategory(List<FileNameAndScoreDTO> fullList, long category){
return fullList.stream()
.filter(f -> Long.compare(f.getCategory(), category) == 0)
.sorted((f1, f2) -> Integer.compare(f2.getScore(), f1.getScore()))
.limit(7)
.map(f -> f.getFile_name())
.collect(Collectors.toList());
}
You can call the function like this. The first parameter is the list with all objects. The second parameter is the number(?) of the category.
List<String> topSevenNamesOrderedByScoreWithCategory1337 = getTopSevenNamesOrderedByScoreDescOfCategory(fileNameAndScoreList, 0l);
Upvotes: 1