【发布时间】:2019-05-29 20:25:13
【问题描述】:
假设我有一个“建议”列表。我需要获得 TOP 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 个。
【问题讨论】:
标签: java arraylist java-stream