As you obviously need a specific implementation of Map, you should use the method Collectors.toMap allowing to provide the mapSupplier instead of toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) because even if behind the scene it will still return an HashMap, it is not specified explicitly into the javadoc so you have no way to be sure that it will still be true in the next versions of Java.
So your code should be something like this:
HashMap<Integer,String> studentHash = studentList.stream().collect(
Collectors.toMap(
s -> s.studentId, s -> s.studentName,
(u, v) -> {
throw new IllegalStateException(
String.format("Cannot have 2 values (%s, %s) for the same key", u, v)
);
}, HashMap::new
)
);
If you don't care about the implementation of the Map, simply use toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) as collector as next:
Map<Integer,String> studentHash = studentList.stream().collect(
Collectors.toMap(s -> s.studentId, s -> s.studentName)
);
toMapmethod inCollectors.