假设我有一个“建议”列表。我需要获取前4个视频ID。
public class Suggestion{
static allSuggestions = new ArrayList<Suggestion>();
int id;
String videoId;
public Suggestion(int id, String videoId){
this.id = id;
this.videoId = videoId;
allSuggestions.add(this);
}
public String getVideoId(){
return videoId;
}
public static List<Suggestion> getAllSuggestions(){
return allSuggestions;
}
}
我尝试过:
Suggestion.getAllSuggestions()
.stream()
.collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))
.ifPresent(System.out::println);
但是它仅返回一个最常见的视频ID,而不返回前4个。
答案 0 :(得分:2)
按计数对降序进行排序,然后使用limit
选择前4个:
Suggestion.getAllSuggestions()
.stream()
.collect(Collectors.groupingBy(Suggestion::getVideoId, Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(Entry::getValue).reversed()) // Sort descending by count
.limit(4) // Top 4 only
.forEach(System.out::println); // Print them, one per line