Collectors#toMap()
I want to use LikedHashMap explicitly. By the way, I want to allow duplicate keys.
	public static <T, K, V> Collector<T, ?, Map<K, V>> toMap(
			Function<? super T, ? extends K> keyMapper,
			Function<? super T, ? extends V> valueMapper) {
		return Collectors.toMap(
				keyMapper,
				valueMapper,
				(a, b) -> b,
				LinkedHashMap::new);
	}
Throw an exception if you don't want to allow duplicate keys.
(a, b) -> { throw new IllegalStateException(~); }
See the standard two-argument Collectors # toMap () for details.
I want to sort naturally by key. almost the same.
	public static <T, K, V> Collector<T, ?, Map<K, V>> toTreeMap(
			Function<? super T, ? extends K> keyMapper,
			Function<? super T, ? extends V> valueMapper) {
		return Collectors.toMap(
				keyMapper,
				valueMapper,
				(a, b) -> b,
				TreeMap::new); //★ Here
	}
When you want to specify Comparator in TreeMap, specify it with a lambda expression instead of a constructor reference.
Collectors#toSet()
The point here is to use toCollection () instead of toSet ().
	public static <T> Collector<T, ?, Set<T>> toSet() {
		return Collectors.toCollection(LinkedHashSet::new);
	}
Basically the same.
	public static <T> Collector<T, ?, Set<T>> toTreeSet() {
		return Collectors.toCollection(TreeSet::new);
	}
Collectors#groupingBy
	public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(
			Function<? super T, ? extends K> classifier) {
		return Collectors.groupingBy(classifier,
				LinkedHashMap::new, //★ Here
				Collectors.toList());
	}
the same.
	public static <T, K> Collector<T, ?, Map<K, List<T>>> orderedGroupBy(
			Function<? super T, ? extends K> classifier) {
		return Collectors.groupingBy(classifier,
				TreeMap::new, //★ Here
				Collectors.toList());
	}
... I can't think of a good method name.
	public static <T, K> Collector<T, ?, Map<K, Set<T>>> groupingBySet(
			Function<? super T, ? extends K> classifier) {
		return Collectors.groupingBy(classifier,
				TreeMap::new,
				Collectors.toCollection(LinkedHashSet::new)); //★ Here
	}
Of course, TreeSet or ordinary Collectors.toSet () can be used depending on the purpose.
	public static <T, K, D> Collector<T, ?, Map<K, List<D>>> groupingBy(
			Function<? super T, ? extends K> classifier,
			Function<? super T, ? extends D> mapper) {
		return Collectors.groupingBy(classifier,
				LinkedHashMap::new,
				Collectors.mapping(mapper, //★ Here
						Collectors.toList()));
	}
Of course, you can use Set instead of List.
Collectors#collectingAndThen
If you want to generate an immutable Map or List.
	public static <T, K, V> Collector<T, ?, Map<K, V>> toConstMap(
			Function<? super T, ? extends K> keyMapper,
			Function<? super T, ? extends V> valueMapper) {
		return Collectors.collectingAndThen(
				Collectors.toMap(
					keyMapper,
					valueMapper),
				Collections::unmodifiableMap);
	}
        Recommended Posts