Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 357
Mr. Noddy Avatar asked Dec 18 '22 21:12

Mr. Noddy


1 Answers

attributeUnitMap = attributesList.stream()
    .filter(a -> a.getAttributeUnit() != null)
    .collect(Collectors.toMap(
        a -> a.getAttributedName() == null ? "" : a.getAttributeName(),
        a -> a.getAttributeUnit()))
like image 52
dolan Avatar answered Dec 21 '22 11:12

dolan