I want to know the difference between using a list with the interface Set < > and the Map interface < > which is better for me to access the data more easily?
I want to know the difference between using a list with the interface Set < > and the Map interface < > which is better for me to access the data more easily?
The difference is the functionality defined for each of these interfaces:
Map
is an interface that defines storing objects in Key pairs (or Key) Value, where you can register, obtain and remove an item from the Key.
Example:
//creamos el mapa
Map<String, Usuario> mapa = new HashMap<>();
//agregamos elementos al mapa
mapa.put("Luiggi Mendoza J", new Usuario(227, "Luiggi Mendoza J", 10.4k));
mapa.put("theboshy", new Usuario(9206, "theboshy", 1));
System.out.println(mapa.get("theboshy")); //imprime datos de usuario
System.out.println(mapa.get("elporfirio")); //imprime nulo
//recorrer todas las entradas llave-valor del mapa
//e imprimir la llave y el valor correspondiente
for (Map.Entry<String, Usuario> entry : mapa.entrySet()) {
System.out.printf(
"Llave: %s. Valor: %s\n",
entry.getKey(), entry.getValue());
}
There can only be 1 Value associated with a Key. This does not mean that there can be 1 Value associated to multiple Keys. Example:
Map<String, String> mapa = new HashMap<>();
mapa.put("saludo", "hola mundo");
System.out.println(mapa.get("saludo")); //imprime 'hola mundo'
String valor = "aloha!";
//reemplazamos el valor de la llave "saludo"
mapa.put("saludo", valor);
System.out.println(mapa.get("saludo")); //imprime 'aloha!'
//asignamos el mismo valor a una nueva llave
mapa.put("saludo efusivo", valor);
System.out.println(mapa.get("saludo"));
System.out.println(mapa.get("saludo efusivo"));
//ambas sentencias imprimieros 'aloha!'
Set
is an interface that defines storing objects as if it were a mathematical set. This allows you to register and remove items from this set, but does not allow to get them one by one. Set
is used primarily to verify that there are no repeated objects in a collection.
Example:
Set<Integer> set = new HashSet<>();
//agregamos elementos
set.add(10);
set.add(5);
set.add(8);
//podemos remover elementos
set.remove(10);
//pero no podemos obtener elementos, no existe un método 'get'
//lo que si, existe un método 'contains' que permite verificar
//si un elemento existe en el set
if (set.contains(5)) {
System.out.println("5 existe");
}
//sin embargo, se pueden recorrer todos los elementos de un set
for (Integer elem : set) {
System.out.println(elem);
}
It should be noted that a Set
can be seen simply as a Map<Object, Boolean>
, where the objects to insert in Set
are the keys of the Map
. This can be verified by using the method Collections#newSetFromMap(Map<E, Boolean>)
.