Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of Objects to map of properties

Tags:

java

java-8

I have a Section class with some attributes as below

class Section {
    private String name;
    private String code;
    // respective getters and setters.
}

Now I have a list of Section Objects and I want to convert the list to a map of name and code. I know it can be done in a regular way as below.

List<Section> sections = getSections();
Map<String, String> nameCodeMap = new HashMap<>();
for (Section section : sections) {
    nameCodeMap.put(section.getCode(), section.getName());
}

I want to know if something similar is possible with Java-8 streams.

like image 945
raviraja Avatar asked Oct 22 '25 16:10

raviraja


1 Answers

Not to difficult. Just use the toMap collector with the appropriate method references to the getters:

sections.stream().collect(
    Collectors.toMap(Section::getName, Section::getCode)
);
like image 190
flakes Avatar answered Oct 24 '25 05:10

flakes