如何从LinkedHashMap获取密钥

时间:2018-06-21 08:35:00

标签: java list key-value linkedhashmap

如何从LinkedHashMap获取密钥?

例如,我有LinkedHashMap,其中包含密钥和用户名,然后我需要在扫描仪的帮助下输入名称,然后我想查看该元素具有什么密钥,即我输入的元素:

static LinkedHashMap<Integer, String> names = new LinkedHashMap<>();
static Scanner sc = new Scanner(System.in);
static int i = 1;
stasic String name;

public static void main(String[] args) {
    int b = 0;
    while (b == 0) {
        System.out.println("Input your name: ");
        name = sc.nextLine;
        names.put(i, name);
        i += 1;
        outName();
    }
}

public static void outName() {
    System.out.println("Input name: ");
    name = sc.nextLine();
    if (names.containsValue(name)) {
        //I do not know what should I do here?
    }
}

2 个答案:

答案 0 :(得分:0)

for (Map.Entry<String, ArrayList<String>> entry : names.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
}

使用Map.Entry进行迭代

答案 1 :(得分:0)

如果要按“设置”中的顺序收集密钥,则如下所示:

map.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toCollection(LinkedHashSet::new));

此处,LinkedHashSet维护LinkedHashMap的插入顺序。 如果使用HashSet,则可能会更改键的顺序。为了确保安全,请使用LinkedHashSet。

同样的情况适用于ArrayList的情况。 ArrayList保持插入顺序,因此不必担心顺序。

map.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toCollection(ArrayList::new));
相关问题