map.entryset java code example

Example 1: getordefault java

Map<String, String> map = new HashMap<>();

    map.put("1", "Foo");
    //search for the entry with key==1, since present, returns foo
    System.out.println(map.getOrDefault("1", "dumnba"));
    //search for the entry with key==2, since not present, returns dumnba
    System.out.println(map.getOrDefault("2", "dumnba"));

Example 2: 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 3: how to instanciate map.entry java

/**
 * @author Jack Waller <[email protected]>
 * @version 1.1
 * @since 2020-03-28
 * A implementation of Map.Entry.
 */
public final class Pair<K, V> implements Map.Entry<K, V> {

    //variables
    private final K key;
    private V value;

    //constructor
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    //methods

    /**
     * Returns the key.
     * @return K
     */
    @Override
    public K getKey() {
        return key;
    }

    /**
     * Returns the value.
     * @return V
     */
    @Override
    public V getValue() {
        return value;
    }

    /**
     * Sets the value, returns the old value
     * @param v value to set
     * @return V
     */
    @Override
    public V setValue(V v) {
        V old = this.value;
        this.value = v;
        return old;
    }
}

Tags:

Java Example