Skip to content

Instantly share code, notes, and snippets.

@DeepSpawn
Last active March 27, 2016 00:55
Show Gist options
  • Save DeepSpawn/21b7a591fccfc6cad6bd to your computer and use it in GitHub Desktop.
Save DeepSpawn/21b7a591fccfc6cad6bd to your computer and use it in GitHub Desktop.
/**
* Returns a collector that will collect the stream into an immutable map.
*
* @param keyMapper A function that given a stream element returns a key
* @param valueMapper A function that given a stream element returns a value
* @param <T> The type of element in the stream
* @param <K> The type of keys used in the map
* @param <V> the type of values contained in the map
* @return a collector that will collect the a stream into an immutable map
*/
public static <T, K, V> Collector<T, Builder<K, V>, Map<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends V> valueMapper) {
return Collector.of(
ImmutableMap::builder,
(b, e) -> b.put(keyMapper.apply(e), valueMapper.apply(e)),
(m1, m2) -> m1.putAll(m2.build()),
Builder::build);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment