java map get value code example

Example 1: java map get the key from value

public static <T, E> Set<T> getKeyByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

Example 2: hashmap get value java

//Import Hashmap
import java.util.HashMap;
   
    HashMap<String, String> dir = new HashMap<String, String>();
//Add key, values  
    dir.put("hi", "hello");
	dir.put("wow", "amazing");
//print value for hi.
    System.out.println(dir.get("hi");

Example 3: map java

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class Main {
   public static void main(String[] args) {

      //La fameuse syntaxe en diamant de Java 7
      Map<Integer, String> hm = new HashMap<>();
      hm.put(10, "1");
      hm.put(20, "2");
      hm.put(30, "3");
      hm.put(40, "4");
      hm.put(50, "5");
      //Ceci va écraser la valeur 5
      hm.put(50, "6");
      
      System.out.println("Parcours de l'objet HashMap : ");
      Set<Entry<Integer, String>> setHm = hm.entrySet();
      Iterator<Entry<Integer, String>> it = setHm.iterator();
      while(it.hasNext()){
         Entry<Integer, String> e = it.next();
         System.out.println(e.getKey() + " : " + e.getValue());
      }
      
      System.out.println("Valeur pour la clé 8 : " + hm.get(8));
      
      Map<Integer, String> lhm = new LinkedHashMap<>();
      lhm.put(10, "1");
      lhm.put(20, "2");
      lhm.put(30, "3");
      lhm.put(40, "4");
      lhm.put(50, "5");
      
      System.out.println("Parcours de l'objet LinkedHashMap : ");      
      Set<Entry<Integer, String>> setLhm = lhm.entrySet();
      Iterator<Entry<Integer, String>> it2 = setLhm.iterator();
      while(it2.hasNext()){
         Entry<Integer, String> e = it2.next();
         System.out.println(e.getKey() + " : " + e.getValue());
      }
   }
}

Example 4: hashmap get value by key java

import java.util.HashMap;
//Within a class
//You can do new HashMap<Key Type, Value Type>();, but you don't need to
HashMap<Int, String> examplehashmap=new HashMap<>();
{
//put in values
 examplehashmap.put(5, "example");
};
//get value
examplehashmap.get(5);
//returns "example"

Example 5: get value of map java

Hash_Map.get(Object key_element)