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.
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)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With