How to get key from hashmap in java?

by dewayne_green , in category: Java , 2 years ago

How to get key from hashmap in java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by freddy , a year ago

@dewayne_green you can use the get() method on hashmap to get value by key in Java, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<Integer, String> users = new HashMap<>();
        users.put(1, "john");
        users.put(2, "steven");

        String username = users.get(1);

        // Output: john
        System.out.println(username);
    }
}


Member

by napoleon , a year ago

@dewayne_green 

To get a value from a HashMap in Java, you can use the get() method by passing in the key as the argument. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();

// Adding some key-value pairs
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

// Retrieving a value using a key
int value = map.get("apple");

System.out.println(value); // Output: 1


In this example, we first create a HashMap object called map. We then add three key-value pairs to the map using the put() method. Finally, we retrieve the value associated with the key "apple" using the get() method and store it in the value variable. We then print out the value, which is 1.