Convert list of Objects to map of properties

raviraja :

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.

davidxxx :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142603&siteId=1