如何从 LinkedHashMap 获取密钥

How to get a key from LinkedHashMap

如何从LinkedHashMap获取key?

例如,我有 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?
    }
}
for (Map.Entry<String, ArrayList<String>> entry : names.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
}

使用Map.Entry迭代

如果你想按照 Set 中的顺序收集键,那么它是这样的:

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));