You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过索引位置获取HashMap中的值?技术问题咨询

How to Get Value by Position from a HashMap in Java

Hey there! I see you're trying to pull a value from your HashMap using an integer index but hitting a roadblock—let me break down why this happens and walk you through solid fixes.

First off, HashMap has no concept of "position" or fixed order for its elements. It’s built for fast lookups using keys, not for accessing entries by their insertion order or index. That’s why you can’t directly grab a value by an int position from a HashMap.

But no worries, here are tailored solutions depending on what you need:

1. Use LinkedHashMap to Preserve Insertion Order

If you need to keep elements in the exact order you added them, swap HashMap for LinkedHashMap. This class maintains insertion order, so you can safely convert its values to a List and access by index.

Here’s your modified code:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class UniversityExample {
    public static void main(String[] args) {
        Map<String,String> uniList = new LinkedHashMap<String, String>();
        uniList.put("UniMe","Università degli studi di Messina");
        uniList.put("UniBa","Università degli studi di Bari");
        uniList.put("UniCz","Università degli studi di Catanzaro");
        uniList.put("UniBas","Università degli studi di Basilicata");
        uniList.put("UniPrt","Università degli studi di Napoli Partenophe");
        // Add your remaining entries here...

        // Convert the map's values to a List
        List<String> universityNames = new ArrayList<>(uniList.values());
        
        // Get value at position 2 (0-indexed, so this is the third element)
        int targetPosition = 2;
        if (targetPosition >= 0 && targetPosition < universityNames.size()) {
            String selectedUni = universityNames.get(targetPosition);
            System.out.println(selectedUni); // Outputs: Università degli studi di Catanzaro
        } else {
            System.out.println("Invalid position—out of bounds!");
        }
    }
}

2. Use TreeMap for Sorted Order

If you want elements sorted by their keys (like alphabetical order of "UniMe", "UniBa", etc.), use TreeMap. Convert its values to a List to access by index:

Map<String,String> uniList = new TreeMap<String, String>();
// Same put operations as before...

List<String> sortedUniNames = new ArrayList<>(uniList.values());
String firstSortedUni = sortedUniNames.get(0); // Will be "UniBa" (since keys are sorted alphabetically)

If you absolutely have to stick with HashMap, you can still convert its values to a List—but a big warning: the order of elements here is unpredictable. It can change between runs or after modifying the map, so only use this if you don’t care which position maps to which value:

List<String> uniValues = new ArrayList<>(uniList.values());
String randomValue = uniValues.get(1); // Result isn't guaranteed to be "UniBa"!

Quick Reminders:

  • Java uses 0-indexing, so position 0 is the first element, position 1 is the second, and so on.
  • Always check if your target index is within the List’s bounds to avoid IndexOutOfBoundsException.

内容的提问来源于stack exchange,提问作者Giorgio Cafiso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:26:55