简体   繁体   中英

How to generate hashmap or hashtable from list of class object using stream map in java8?

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.

Something like this:

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

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)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM