Skip to content

Instantly share code, notes, and snippets.

@danielalexiuc
Created December 11, 2015 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielalexiuc/6657632a7148c5eaef3f to your computer and use it in GitHub Desktop.
Save danielalexiuc/6657632a7148c5eaef3f to your computer and use it in GitHub Desktop.
Java 8 Stream Collectors that should have been in the JDK from the start!
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
/**
* Just some stuff that the JDK is missing :rolleyes:
*/
public class MoreCollectors {
/**
* Collect a stream into a LinkedHashMap using the identity function
*/
public static <T> Collector<T, ?, Map<T, T>> toLinkedMap() {
return toLinkedMap(identity(), identity());
}
/**
* Collect a stream into a LinkedHashMap, using the specified mappers
*/
public static <T, K, U> Collector<T, ?, Map<K, U>> toLinkedMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper,
(o, o2) -> {
throw new IllegalStateException(String.format("Duplicate key %s", o));
},
LinkedHashMap::new);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment