简体   繁体   中英

How to get a key from LinkedHashMap

How to get a key from LinkedHashMap?

For example I have LinkedHashMap which contains key and user names and I need to input name with the help of scanner after that I want to see what key that element has, the element that I input:

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

use Map.Entry to iterate

If you want to collect the keys in order they are in Set then it is like this:

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

Here the LinkedHashSet maintains the order of insertion of LinkedHashMap. If you use HashSet it may change the order of keys. For surety use LinkedHashSet.

Same thing is applicable on case of ArrayList. ArrayList maintains the insertion order, so nothing to worry about order.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM