有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从HashMap中的数组中检索值的单行代码

所以我在Java中工作,我有一个HashMap,它用整数数组存储字符串键。这就是宣言的内容:

public HashMap<String, int[]> playerPoints = new HashMap<String, int[]>();

我的问题是,是否可以在一行简单的代码中检索某个键的数组的第一个整数。我明白我可以这样做:

tempArray = playerPoints.get(String);
int firstValue = tempArray[0];

但是有没有一种方法可以在一行代码中实现呢


共 (2) 个答案

  1. # 1 楼答案

        Integer[] myArr = {2, 3, 5};
    
        HashMap<String, Integer[]> hashMap = new HashMap<>();
        hashMap.put("el", myArr);
        System.out.println(hashMap.get("el")[0].toString());
    

    输出将为2

  2. # 2 楼答案

    您可以在一行中创建它,例如使用默认值0

    int firstValue = playerPoints.isEmpty() ? 0 : playerPoints.get("String").length == 0 ? 0 : playerPoints.get("String")[0];