英文:
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<String>)
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<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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论