Qew
Qew

Reputation: 31

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?
    }
}

Upvotes: 3

Views: 15408

Answers (3)

Olavi Vaino
Olavi Vaino

Reputation: 451

Answer to question "How to get a key from LinkedHashMap?"

names.entrySet().stream().findFirst().get().getKey();

Upvotes: 1

Atul
Atul

Reputation: 3357

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

Upvotes: 0

Konzern
Konzern

Reputation: 128

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

use Map.Entry to iterate

Upvotes: 1

Related Questions