【问题标题】:How to get last index in a map with some null items如何获取包含一些空项目的地图中的最后一个索引
【发布时间】:2020-09-18 07:09:24
【问题描述】:

我有一个Map(int,List<String>),里面的一些列表是空的,例如:

{1 = [example1, 2000, May 22, 2020] , 2 = [example2, 120, May 30, 2020] , 4 = [example3, 120, May 30, 2020]}

所以在我的示例中,索引 3 中的列表为空。

所以我想在我的示例中获得地图中的最高索引,它将是 4。

【问题讨论】:

  • Map(int,List<String>)Map<Integer,List<String>> ?

标签: java android list arraylist hashmap


【解决方案1】:

您可以使用keySet() 获取所有密钥并使用Collections.max 获取最大索引

int maxSet = Collections.max(map.keySet()); 

【讨论】:

    【解决方案2】:

    使用 Java 8 流

    您可以通过地图的keyset 进行流式传输,并在该流上调用 max 操作。检查下面的sn-p:

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class HighestValueInMap {
        public static void main(String[] args) {
            Map<Integer, List<String>> exampleMap = new HashMap<>();
            exampleMap.put(1, Arrays.asList("example1", "2000", "May 22", "2020"));
            exampleMap.put(2, Arrays.asList("example2", "120", "May 30", "2020"));
            exampleMap.put(4, Arrays.asList("example3", "120", "May 30", "2020"));
            System.out.println("exampleMap is = " + exampleMap);
            Integer max = exampleMap.keySet().stream().mapToInt(v -> v).max().getAsInt();
            System.out.println("The max value present in the map is = " + max);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-03
      • 2016-12-23
      • 1970-01-01
      • 2021-06-17
      • 2011-12-14
      • 2017-11-11
      • 2016-02-16
      • 2017-05-08
      相关资源
      最近更新 更多