Being relatively new to Java 8 I would like to know why it allows first variant(merge
function not necessary) of Collectors.toMap()
when working with List
:
static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
A List
allows ENTIRELY DUPLICATE values. Imagine a use case where a developer uses stream
to convert List
to Map
and java 8 exposes the RUNTIME as:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key ...
Shouldn't this scenario be required to be catched at compile time? AFAIK, hashmap used to simply replace old Entry
when a duplicate key
is put. If a developer is sure of the duplicate values in data and wants to handle this exception as a warning, won't he first use Set
instead of List
?
Eg. :-
public class Employee{
public String name;
public String surname;
public Employee(String firstname, String secondName) {
this.name=firstname;this.surname=secondName;
}
public boolean equals(Object o){
return (o instanceof Employee) && ((Employee)o).name.equals(this.name) && ((Employee)o).surname.equals(this.surname);
}
public int hashCode(){
return (name+surname).toCharArray().length;
}
public String primaryKey(){
return this.name;
}
public static void main(String[] args){
Set<Employee> set = new HashSet<>();
ArrayList<Employee> list = new ArrayList<>();
Employee one = new Employee("firstname","secondName");
Employee two = new Employee("firstname","secondName");
list.add(one);list.add(two); //allows entirely duplicate
Map<String,Employee> hashMap = new HashMap<>();
for(Employee employee:list){
//replace old employees in the order maintained by list before java 8
hashMap.put(employee.primaryKey(), employee);
//or may be use list inside some hashmap
}
set.add(one);set.add(two); //we can handle duplicates just by using sets
Map<String,Employee> dontNeedListAsValues=set.stream().collect(Collectors.toMap(Employee::primaryKey,o->o));
Map<String, Employee> needListAsValues=list.stream().collect(Collectors.toMap(Employee::primaryKey, o -> o)); //currently ALLOWED for LIST
}
}
question from:
https://stackoverflow.com/questions/65647774/why-allow-list-conversion-to-map-without-merge-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…