Mapping classes with lambda to default value

Viewed 423

Follow up question from this. Having a hierarchy like this. Where the A is the base class:

       A 
      / \
     B   C

  |   A    |   |   B       |   |  C      |  
  | getId()|   |A.getId()  |   |A.getId()|
               |isVisible()| 

and the following content:

List<A> mappings;

I would like to map all IDs of instances of B to the value of B.isVisible() and the IDs of instances of C to TRUE

With the help of the initial question, I refined it to this format:

mappings.stream().filter(a -> a instanceof B)
                 .map(b -> (B)b)
                 .collect(Collectors.toMap(A::getId, m -> m.isVisible()));

The ugly version is:

mappings.stream()                       
        .collect(Collectors.toMap(A::getId, m ->
                        {
                            boolean isB = m instanceof B;
                            return isB ? ((B) m).isVisible() : true;
                        }));

Any help on improving it to provide the default true for the more elegant version?

6 Answers
Related