0
class Student {
    int studentId;
    String studentName;
    String studentDept;
    public Student() {}
}

I have these student object list that is,

List<Student> studentList;

I want to generate hash map from these student list object.

HashMap<Integer,String> studentHash;

hashmap contain sudentid and name list key value pair.

2
  • what should be the map key and value? Commented Nov 17, 2016 at 15:13
  • 4
    What have you tried? This is not a code writing service. Here's a hint: Look at the toMap method in Collectors. Commented Nov 17, 2016 at 15:14

2 Answers 2

3

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)
);
Sign up to request clarification or add additional context in comments.

Comments

3

Something like this:

studentList.stream().collect(
    Collectors.toMap(Student::getStudentId, Student::getStudentName)
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.