java - How to genarate 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 is,

list<student> studentlist; 

i want generate hash map these student list object.

hashmap<integer,string> studenthash; 

hashmap contain sudentid , name list key value pair.

as need specific implementation of map, should use method collectors.tomap allowing provide mapsupplier instead of tomap(function<? super t,? extends k> keymapper, function<? super t,? extends u> valuemapper) because if behind scene still return hashmap, not specified explicitly javadoc have no way sure still true in next versions of java.

so code should 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) same key", u, v)             );         }, hashmap::new     ) ); 

if don't care implementation of map, use tomap(function<? super t,? extends k> keymapper, function<? super t,? extends u> valuemapper) collector next:

map<integer,string> studenthash = studentlist.stream().collect(     collectors.tomap(s -> s.studentid, s -> s.studentname) ); 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -