为什么在没有合并功能的情况下允许 List 转换为 Map?

Pra*_*aur -1 java arraylist hashmap java-8 collectors

相对较新到Java 8,我想知道为什么它允许第一个变体(merge功能不是必要的)Collectors.toMap()一起工作时List

static <T,K,U> Collector<T,?,Map<K,U>>  toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
Run Code Online (Sandbox Code Playgroud)

AList允许完全重复的值。想象一个用例,其中开发人员用于stream转换ListMapJava 8 将 RUNTIME 公开为:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key ...
Run Code Online (Sandbox Code Playgroud)

不应该要求在编译时捕获这种情况吗?AFAIK,哈希图用于在放置Entry重复项时简单地替换旧的key。如果开发人员确定数据中存在重复值并希望将此异常作为警告处理,他会不会首先使用Set代替List?例如。:-

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 8

这不是一回事有几个原因:

  • 只有一种Stream类型,在List和之间是相同的Set
  • 只有一种Collector类型,因此不同的Collectors 不能仅适用于特定类型的流。
  • 最后,Set当您知道键是唯一的时,转换为 a 的开销很大,并且对于这种特定情况通常不值得。