我有一个LinkedHashMap,我正在try 拆分它的键和值,并引用键集中的特定键或值集中的值.为了前任. 假设我有以下LinkedHashMap:

4|2

3|1

我希望函数返回1,这是集合中索引为1的值,如果索引=0,则返回2. 对于另一个函数,我希望得到3作为值,在键值中使用索引1. 因此,基本上从LinkedHashMap创建一个仅包含值/键的数组,然后在该数组中查找某个给定位置. 我的代码如下所示:

    public static Integer getLHMValue(Map<Integer, Long> lhm, int index) { 
        Set<Map.Entry<Integer, Long>> valueSet = lhm.entrySet();
        Integer[] valueArray = valueSet.toArray(new Integer[valueSet.size()]);
        Integer value = valueArray[index];
        return value;
    }

    public static Integer getLHMKey(Map<Integer, Long> lhm, int index) { 
        Set<Integer> keySet = lhm.keySet();
        Integer[] keyArray = keySet.toArray(new Integer[keySet.size()]);
        Integer key = keyArray[index];
        return key;
}

不过,我在以下位置获得了java.lang.ArrayStoreException:java.util.LinkedHashMap$条目: Integer[]密钥数组=valueSet.toArray(new Integer[valueSet.size()]);. 有什么主意吗?

推荐答案

问题是,如果要首先拥有一个包含Map.Entry的数组,则需要使用entry Set.为这两种方法保留这样的数组会更快.

List<Map.Entry<Integer, Long>> entries = new ArrayList<>(lhm.entrySet());

public static long getLHMValue(Map<Integer, Long> lhm, int index) { 
    return entries.get(index).getValue();
}

public static int getLHMKey(Map<Integer, Long> lhm, int index) { 
    return entries.get(index).getKey();
}

如果直接这样做,没有有效的解决方案,因此不建议提供这些函数来访问键和值.

public static Long getLHMValue(Map<Integer, Long> lhm, int index) { 
    return lhm.entrySet().stream()
        .map(Map.Entry<Integer, Long>::getValue)
        .skip(index)
        .findFirst()
        .orElseThrow(IndexOutOfBoundsException::new);
}

public static Integer getLHMKey(Map<Integer, Long> lhm, int index) { 
    return lhm.entrySet().stream()
        .map(Map.Entry<Integer, Long>::getKey)
        .skip(index)
        .findFirst()
        .orElseThrow(IndexOutOfBoundsException::new);
}

Java相关问答推荐

无法在Java中使用Curve secp 256 k1验证JWT

Jooq隐式地将bigint转换为数字,并且索引不起作用

如何让TaskView总是添加特定的列来进行排序?

@从类文件中删除JsonProperty—Java

inteliJ中是否有一个功能可以自动在块注释中的/*后面添加一个空格?''

Java 8中的多个字段和计数

使用java访问具体子类特定方法的最佳方法是什么?

Spark上下文在向Spark提交数据集时具有内容,但Spark在实际构建它时发现它为空

如何从错误通道回复网关,使其不会挂起

多重延迟签名

把一条整型短裤和两条短裤装成一条长的

Jenv-相同的Java版本,但带有前缀

基于接口的投影、原生查询和枚举

Docker不支持弹性APM服务器

我的Spring Boot测试显示&IlLegalStateException:无法加载某事的ApplicationContext.

try 将JSON字符串响应从API转换为映射字符串、对象>;时出错

try 在Android Studio中的infoWindow中使用EditText(Java)

为什么StandardOpenOption.CREATE不能通过Ubuntu在中小企业上运行?

在ECLIPSE上的M1 Pro上运行JavaFX的问题

无法在Java中获取ElastiCache的AWS CloudWatch指标