I have this code to get map:
List myList = myMethod.getList();
myList.stream().collect(
Collectors.toMap(
MyObject::getKey,
As explained in this answer, this is a known issue that is going to be fixed in Java 9—at least for the toMap collector that doesn’t accept a merge function.
Since the merge function only receives the two values to be merged and signature can’t be easily changed, there is no fix for these overloaded methods in sight. Unfortunately, there is no toMap collector which accepts a Map Supplier without an explicit merge function, so unless this will change until the release, there will be no fix for your scenario where a LinkedHashMap should be returned.
So the solution is to implement your own collector. Then, you don’t have to wait for Java 9 and don’t risk to get disappointed.
static > Collector toMap(
Function keyExtractor, Function valueExtractor, Supplier mapSupplier) {
return Collector.of(mapSupplier,
(m, t) -> putUnique(m, keyExtractor.apply(t), valueExtractor.apply(t)),
(m1,m2)-> { m2.forEach((k, v) -> putUnique(m1, k, v)); return m1; }
);
}
private static void putUnique(Map map, K key, V v1){
V v2 = map.putIfAbsent(key, v1);
if(v2 != null) throw new IllegalStateException(
String.format("Duplicate key %s (values %s and %s)", key, v1, v2));
}
You can use this collector as
LinkedHashMap map = myList.stream()
.collect(toMap(MyObject::getKey, MyObject::getValue, LinkedHashMap::new));
or use a qualified MyCollector.toMap, referring to the class where you put that custom collector.