Created
December 11, 2015 00:28
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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