Sobes.tech
Junior

Come ottenere l'unico elemento da una Lista? Come ottenere l'unico elemento da un Set se get(0) non esiste?

sobes.tech AI

Risposta dell'AI

Se hai una lista (List) e sei sicuro che ci sia esattamente un elemento, puoi ottenere quell’elemento tramite l’indice 0:

List<String> list = Arrays.asList("elemento");
String element = list.get(0);

Per un insieme (Set), non esiste accesso tramite indice, poiché Set non è ordinato. Per ottenere l’unico elemento di un Set, puoi usare un iteratore:

Set<String> set = new HashSet<>();
set.add("elemento");
String element = set.iterator().next();

È importante assicurarsi che ci sia effettivamente un solo elemento nel Set, altrimenti next() potrebbe lanciare un’eccezione o restituire un elemento sbagliato.