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 don't have Section
elements that have the same getCode() value :
Map<String, String> map = sections.stream()
.collect(toMap(Section::getCode, Section::getName);
If you have Section
elements that have the same getCode() value, the previous one will raise IllegalStateException
because it doesn't accept that. So you have to merge them.
For example to achieve the same thing than your actual code, that is overwriting the existing value for an existing key, use this overload :
toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
and return the second parameter of the merge function :
Map<String, String> map = sections.stream()
.collect(toMap(Section::getCode, Section::getName, (a, b) -> b);
Please find below code for the dame :
List<Section> sections = Arrays.asList(new Section("Pratik", "ABC"),
new Section("Rohit", "XYZ"));
Map<String, String> nameCodeMap = sections.stream().collect(
Collectors.toMap(section -> section.getName(),
section -> section.getCode()));
nameCodeMap.forEach((k, v) -> System.out.println("Key " + k + " " + "Value " + v));
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.