【问题标题】:Find top 4 most common object in list在列表中查找前 4 个最常见的对象
【发布时间】: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


    【解决方案1】:

    按计数对条目进行降序排序,然后使用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
    

    【讨论】:

    • 你也可以使用.sorted(Map.Entry.&lt;String, Long&gt;comparingByValue().reversed())
    • @PaulLemarchand 或 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2017-09-22
    • 2017-04-21
    • 2010-12-03
    相关资源
    最近更新 更多