简体   繁体   中英

Converting List to Map in java based on condition using stream operations

I am trying to convert List to HashMap using stream. Here is my code..

attributeUnitMap = attributesList.stream()
    .filter(a -> a.getAttributeUnit() != null)
    .collect(Collectors.toMap(Attribute::getAttributeName, a -> a.getAttributeUnit()));

Now I want to add condition that, if I get attribute name null then item should be added to map with blank string as follows (any_attributeName, "").

How can I achieve this using stream operation. I know I can check if attribute name is null by using filter condition but can I add blank string if it is null. Is it possible? if not, why so? Please help.

attributeUnitMap = attributesList.stream()
    .filter(a -> a.getAttributeUnit() != null)
    .collect(Collectors.toMap(
        a -> a.getAttributedName() == null ? "" : a.getAttributeName(),
        a -> a.getAttributeUnit()))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM