Skip to content

Instantly share code, notes, and snippets.

@HoweChen
Last active January 1, 2020 09:14
Show Gist options
  • Save HoweChen/533185dfde92c677f19d6745ae54bbc7 to your computer and use it in GitHub Desktop.
Save HoweChen/533185dfde92c677f19d6745ae54bbc7 to your computer and use it in GitHub Desktop.
[zip two lists to map]#Java
// both are good to use, but cannot tolerate the situation when key or value inside the list is null
public static <K, V> Map<K, V> zipToMap(List<K> keys, List<V> values) {
return IntStream.range(0, keys.size()).boxed()
.collect(Collectors.toMap(keys::get, values::get));
}
public static <K, V> Map<K, V> zipToMap(List<K> keys, List<V> values) {
Iterator<K> keyIter = keys.iterator();
Iterator<V> valIter = values.iterator();
return IntStream.range(0, keys.size()).boxed()
.collect(Collectors.toMap(_i -> keyIter.next(), _i -> valIter.next()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment