在列表中找到最常见的4个对象

时间:2019-05-29 20:25:13

标签: java arraylist java-stream

假设我有一个“建议”列表。我需要获取前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个。

1 个答案:

答案 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