Mr. Noddy
Mr. Noddy

Reputation: 1590

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.

Upvotes: 4

Views: 7537

Answers (1)

dolan
dolan

Reputation: 1804

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

Upvotes: 11

Related Questions