如何在具有一些空项的映射中获取最后一个索引

huangapple go评论73阅读模式
英文:

How to get last index in a map with some null items

问题

我得到了一个Map(int,List<String>),其中一些列表内部是空的,例如:

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

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

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

英文:

I got a Map(int,List&lt;String&gt;) and some of the lists inside are null for example:

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

so in my example the list in index 3 is null.

so I want do get the highest index in the map in my example it'll be 4.

答案1

得分: 1

你可以使用 keySet() 来获取所有键,并使用 Collections.max 来获取最大索引。

int maxSet = Collections.max(map.keySet());
英文:

You can use keySet() to get all key and use Collections.max to get max index

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

答案2

得分: 0

使用Java 8流。您可以对地图的keyset进行流处理,并在该流上调用max操作。请查看下面的代码片段:

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);
    }
}
英文:

Using Java 8 stream.

You can stream over the keyset of the map and call the max operation on that stream. Check the snippet below:

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&lt;Integer, List&lt;String&gt;&gt; exampleMap = new HashMap&lt;&gt;();
        exampleMap.put(1, Arrays.asList(&quot;example1&quot;, &quot;2000&quot;, &quot;May 22&quot;, &quot;2020&quot;));
        exampleMap.put(2, Arrays.asList(&quot;example2&quot;, &quot;120&quot;, &quot;May 30&quot;, &quot;2020&quot;));
        exampleMap.put(4, Arrays.asList(&quot;example3&quot;, &quot;120&quot;, &quot;May 30&quot;, &quot;2020&quot;));
        System.out.println(&quot;exampleMap is = &quot; + exampleMap);
        Integer max = exampleMap.keySet().stream().mapToInt(v -&gt; v).max().getAsInt();
        System.out.println(&quot;The max value present in the map is = &quot; + max);
    }
}

huangapple
  • 本文由 发表于 2020年5月31日 03:17:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/62107560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定