【问题标题】:How to find max value of a map whose value is a List in Java8? [closed]如何在 Java 8 中找到其值为 List 的地图的最大值? [关闭]
【发布时间】:2019-01-07 06:13:14
【问题描述】:

我有一个Map

Map<String, ArrayList<Students>> studentsInClass

我可以通过迭代Map 并将其分配给int 并进行比较来找到具有最大数量Students 的类。

我想知道最佳的 Java 8 方法是什么。我想获得Map 中所有值的最大List 大小。

【问题讨论】:

  • 1.程序接口 -- List&lt;Student&gt; 2. 分享你尝试过的和没用的。
  • 想要的输出是什么?
  • 您可以轻松地使用 Java 8 中的powerful Stream API

标签: java collections java-8 hashmap java-stream


【解决方案1】:

我只想获得地图中最大的列表大小

如果我理解你的意思,那么你应该试试这个:

int maxSize = studentsInClass.values()
                             .stream()
                             .map(List::size)
                             .max(naturalOrder())
                             .orElse(0);

【讨论】:

    【解决方案2】:

    Stream 有一个max 方法,可以根据Stream 的元素的任意属性,找到Streammax 元素。

    String largestClassName = 
        studentsInClass.entrySet()
                       .stream()
                       .max(Comparator.comparingInt(e -> e.getValue().size()))
                       .map(Map.Entry::getKey)
                       .orElse(null); // default value for when the Map is empty
    

    或(没有默认值):

    Optional<String> largestClassName = 
        studentsInClass.entrySet()
                       .stream()
                       .max(Comparator.comparingInt(e -> e.getValue().size()))
                       .map(Map.Entry::getKey);
    

    或者,如果您需要最大类的大小(而不是该类的名称):

    int maxClassSize = 
        studentsInClass.values()
                       .stream()
                       .mapToInt(List::size)
                       .max();
                       .orElse(0); // default value for when the Map is empty
    

    或(没有默认值):

    OptionalInt maxClassSize = 
        studentsInClass.values()
                       .stream()
                       .mapToInt(List::size)
                       .max();
    

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 2015-02-18
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多