Comment conserver l'ordre d'itération d'une liste lors de l'utilisation de Collections.toMap() sur un flux?
Je crée un Map à partir d'un List comme suit:
List<String> strings = Arrays.asList("a", "bb", "ccc");
Map<String, Integer> map = strings.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
Je veux garder le même ordre d'itération que dans le List. Comment puis-je créer un LinkedHashMap en utilisant les méthodes Collectors.toMap()?
37
demandé sur
Michael
2015-03-17 05:22:41
2 réponses
La version à 2 Paramètres de Collectors.toMap() utilise un HashMap:
public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper)
{
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
Pour utiliser la version à 4 Paramètres , Vous pouvez remplacer:
Collectors.toMap(Function.identity(), String::length)
Avec:
Collectors.toMap(
Function.identity(),
String::length,
(u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
},
LinkedHashMap::new
)
Ou pour le rendre un peu plus propre, écrivez une nouvelle méthode toLinkedMap() et utilisez-la:
public class MoreCollectors
{
public static <T, K, U> Collector<T, ?, Map<K,U>> toLinkedMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper)
{
return Collectors.toMap(
keyMapper,
valueMapper,
(u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
},
LinkedHashMap::new
);
}
}
65
répondu
prunge
2018-07-06 16:42:18
Vous pouvez facilement y parvenir en passant le vôtre Supplier, Accumulator et Combiner à la méthode collect de votre flux comme ci-dessous:
final LinkedHashMap<String, Integer> map = strings.stream()
.collect(
LinkedHashMap::new, //Supplier
(mapp, itemVar) -> mapp.put(itemVar, itemVar.length()), //Accumulator
Map::putAll //Combiner
);
9
répondu
Mitchapp
2018-07-06 16:47:09