Java: Come convertire List per Map
-
30-09-2019 - |
Domanda
Di recente ho conversazione con un collega su quello che sarebbe il modo ottimale per convertire List
a Map
in Java e se ci sono vantaggi specifici di farlo.
Voglio sapere approccio conversione ottimale e sarebbe davvero apprezzare se qualcuno mi può guidare.
E 'questo approccio buono:
List<Object[]> results;
Map<Integer, String> resultsMap = new HashMap<Integer, String>();
for (Object[] o : results) {
resultsMap.put((Integer) o[0], (String) o[1]);
}
Soluzione
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);
Supponendo, naturalmente, che ogni elemento ha un metodo getKey()
che restituisce una chiave del tipo corretto.
Altri suggerimenti
java-8 , sarete in grado di fare questo in una sola riga utilizzando flussi , e il classe Collectors
.
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
breve demo:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test{
public static void main (String [] args){
List<Item> list = IntStream.rangeClosed(1, 4)
.mapToObj(Item::new)
.collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]
Map<String, Item> map =
list.stream().collect(Collectors.toMap(Item::getKey, item -> item));
map.forEach((k, v) -> System.out.println(k + " => " + v));
}
}
class Item {
private final int i;
public Item(int i){
this.i = i;
}
public String getKey(){
return "Key-"+i;
}
@Override
public String toString() {
return "Item [i=" + i + "]";
}
}
Output:
Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]
Come notato nei commenti, è possibile utilizzare al posto di Function.identity()
item -> item
, anche se trovo i -> i
piuttosto esplicito.
E per essere completa nota che è possibile utilizzare un operatore binario se la funzione non è biunivoca. Per esempio prendiamo in considerazione questo List
e la funzione di mappatura che, per un valore int, calcolare il risultato di essa modulo 3:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));
Quando si esegue questo codice, si otterrà un errore che dice java.lang.IllegalStateException: Duplicate key 1
. Questo perché 1% 3 è uguale a 4% 3 e quindi hanno lo stesso valore di chiave data la funzione di mappatura chiave. In questo caso è possibile fornire un operatore di unione.
Ecco un tale somma dei valori; (i1, i2) -> i1 + i2;
che può essere sostituito con il Integer::sum
metodo di riferimento.
Map<String, Integer> map =
intList.stream().collect(toMap(i -> String.valueOf(i % 3),
i -> i,
Integer::sum));
che ora uscite:
0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)
Speranza che aiuta! :)
Nel caso in cui tale questione non è chiusa come un duplicato, la risposta giusta è quella di utilizzare Google Collezioni :
Map<String,Role> mappedRoles = Maps.uniqueIndex(yourList, new Function<Role,String>() {
public String apply(Role from) {
return from.getName(); // or something else
}});
Dato che Java 8, la risposta da @ZouZou usando il collettore Collectors.toMap
è certamente il modo idiomatico per risolvere questo problema.
E come questo è un compito così comune, si può fare in un programma di utilità statica.
In questo modo la soluzione diventa veramente un one-liner.
/**
* Returns a map where each entry is an item of {@code list} mapped by the
* key produced by applying {@code mapper} to the item.
*
* @param list the list to map
* @param mapper the function to produce the key from a list item
* @return the resulting map
* @throws IllegalStateException on duplicate key
*/
public static <K, T> Map<K, T> toMapBy(List<T> list,
Function<? super T, ? extends K> mapper) {
return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}
Ed ecco come si usa su un List<Student>
:
Map<Long, Student> studentsById = toMapBy(students, Student::getId);
Utilizzo di Java 8 si può fare seguente:
Map<Key, Value> result= results
.stream()
.collect(Collectors.toMap(Value::getName,Function.identity()));
Value
può essere qualsiasi oggetto che si usa.
Un List
e Map
sono concettualmente diversi. Una List
è una collezione ordinata di elementi. Gli articoli possono contenere duplicati, e un elemento potrebbero non avere alcun concetto di un identificativo univoco (chiave). Un Map
ha valori mappati chiavi. Ogni tasto può puntare a un solo valore.
Pertanto, in base alle voci del List
, si può o non può essere possibile convertirlo in un Map
. Does articoli del tuo List
non hanno duplicati? Ogni articolo ha una chiave univoca? Se è così allora è possibile metterli in un Map
.
V'è anche un modo semplice di fare questo usando Maps.uniqueIndex (...) da Google guava librerie
Alexis ha già postato una risposta in Java 8 con il metodo toMap(keyMapper, valueMapper)
. Come da doc per questa implementazione del metodo:
Non ci sono garanzie sul tipo, mutevolezza, serializzabilità, o thread-sicurezza del Map restituito.
Quindi, nel caso in cui siamo interessati in una specifica implementazione di Map
interfaccia per esempio HashMap
allora possiamo utilizzare il modulo di sovraccarico come:
Map<String, Item> map2 =
itemList.stream().collect(Collectors.toMap(Item::getKey, //key for map
Function.identity(), // value for map
(o,n) -> o, // merge function in case of conflict with keys
HashMap::new)); // map factory - we want HashMap and not any Map implementation
Anche se utilizzando Function.identity()
o i->i
va bene ma sembra Function.identity()
invece di i -> i
potrebbe risparmiare un po 'di memoria di cui al presente relativa risposta .
metodo universale
public static <K, V> Map<K, V> listAsMap(Collection<V> sourceList, ListToMapConverter<K, V> converter) {
Map<K, V> newMap = new HashMap<K, V>();
for (V item : sourceList) {
newMap.put( converter.getKey(item), item );
}
return newMap;
}
public static interface ListToMapConverter<K, V> {
public K getKey(V item);
}
Senza java-8, sarete in grado di fare questo in collezioni una linea Commons, e la classe di chiusura
List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map = new HashMap<Key, Item>>(){{
CollectionUtils.forAllDo(list, new Closure() {
@Override
public void execute(Object input) {
Item item = (Item) input;
put(i.getKey(), item);
}
});
}};
Molte soluzioni vengono in mente, a seconda di ciò che si vuole achive:
Ogni Lista elemento è la chiave e il valore
for( Object o : list ) {
map.put(o,o);
}
elementi List hanno qualcosa da guardare in su, forse un nome:
for( MyObject o : list ) {
map.put(o.name,o);
}
elementi List hanno qualcosa da guardare in su, e non v'è alcuna garanzia che essi sono unici: Uso Googles MultiMaps
for( MyObject o : list ) {
multimap.put(o.name,o);
}
Dare a tutti gli elementi della posizione come chiave:
for( int i=0; i<list.size; i++ ) {
map.put(i,list.get(i));
}
...
Dipende da cosa si vuole achive.
Come si può vedere dagli esempi, una mappa è una mappatura da una chiave a un valore, mentre l'elenco è solo una serie di elementi che hanno una posizione di ciascuno. Quindi non sono semplicemente a conversione automatica.
Ecco un metodo poco che ho scritto proprio per questo scopo. Esso utilizza Convalida dal Apache Commons.
Sentitevi liberi di usarlo.
/**
* Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
* the value of the key to be used and the object itself from the list entry is used as the
* objct. An empty <code>Map</code> is returned upon null input.
* Reflection is used to retrieve the key from the object instance and method name passed in.
*
* @param <K> The type of the key to be used in the map
* @param <V> The type of value to be used in the map and the type of the elements in the
* collection
* @param coll The collection to be converted.
* @param keyType The class of key
* @param valueType The class of the value
* @param keyMethodName The method name to call on each instance in the collection to retrieve
* the key
* @return A map of key to value instances
* @throws IllegalArgumentException if any of the other paremeters are invalid.
*/
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
final Class<K> keyType,
final Class<V> valueType,
final String keyMethodName) {
final HashMap<K, V> map = new HashMap<K, V>();
Method method = null;
if (isEmpty(coll)) return map;
notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));
try {
// return the Method to invoke to get the key for the map
method = valueType.getMethod(keyMethodName);
}
catch (final NoSuchMethodException e) {
final String message =
String.format(
Messages.getString(METHOD_NOT_FOUND),
keyMethodName,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
try {
for (final V value : coll) {
Object object;
object = method.invoke(value);
@SuppressWarnings("unchecked")
final K key = (K) object;
map.put(key, value);
}
}
catch (final Exception e) {
final String message =
String.format(
Messages.getString(METHOD_CALL_FAILED),
method,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
return map;
}
È possibile sfruttare i flussi API di Java 8.
public class ListToMap {
public static void main(String[] args) {
List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));
Map<String, User> map = createHashMap(items);
for(String key : map.keySet()) {
System.out.println(key +" : "+map.get(key));
}
}
public static Map<String, User> createHashMap(List<User> items) {
Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return map;
}
}
Per maggiori dettagli visita: http://codecramp.com / java-8-stream-api-convert-list-map /
Come già detto, in java-8 abbiamo la soluzione concisa da Collezionisti:
list.stream().collect(
groupingBy(Item::getKey)
)
ed inoltre, è possibile nidificare gruppo multiplo superamento di un altro metodo groupingBy come secondo parametro:
list.stream().collect(
groupingBy(Item::getKey, groupingBy(Item::getOtherKey))
)
In questo modo, avremo mappa a più livelli, in questo modo: Map<key, Map<key, List<Item>>>
Un Java 8 esempio per convertire un List<?>
di oggetti in un Map<k, v>
:
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));
//example 1
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));
System.out.println("Result 1 : " + result1);
//example 2
Map<Integer, String> result2 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));
Codice copiato da:
https://www.mkyong.com/java8/java -8-convert-list-a-map /
Mi piace la risposta di Kango_V, ma penso che sia troppo complesso. Penso che questo sia più semplice - forse troppo semplice. Se inclinata, è possibile sostituire String con un pennarello generico, e farlo funzionare per qualsiasi tipo di chiave.
public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
Map<String, E> newMap = new HashMap<String, E>();
for( E item : sourceList ) {
newMap.put( converterInterface.getKeyForItem( item ), item );
}
return newMap;
}
public interface ListToMapConverterInterface<E> {
public String getKeyForItem(E item);
}
Utilizzato in questo modo:
Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
new ListToMapConverterInterface<PricingPlanAttribute>() {
@Override
public String getKeyForItem(PricingPlanAttribute item) {
return item.getFullName();
}
} );
Apache Commons MapUtils.populateMap
Se non si utilizza Java 8 e non si desidera utilizzare un ciclo esplicito per qualche motivo, provare MapUtils.populateMap
da Apache Commons.
Diciamo che avete un elenco di Pair
s.
List<ImmutablePair<String, String>> pairs = ImmutableList.of(
new ImmutablePair<>("A", "aaa"),
new ImmutablePair<>("B", "bbb")
);
E ora si desidera una mappa della chiave del Pair
all'oggetto Pair
.
Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {
@Override
public String transform(Pair<String, String> input) {
return input.getKey();
}
});
System.out.println(map);
dà in uscita:
{A=(A,aaa), B=(B,bbb)}
Detto questo, un ciclo for
è forse più facile da capire. (Ciò che segue riporta lo stesso output):
Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
map.put(pair.getKey(), pair);
}
System.out.println(map);