0
votes

I have a following java bean in my application

public class Status{

      private String statusType;
      private String status;
      private String statusCode;
      //getters and setters 
}


public class Associate{
        private String name;
        private String id;
        private List<Status> statuses;
        //getters & setters
 }

And possible values for Status.statusTypes are {"O", "P", "R", "S", "A"}. Now I need to map statuses as part of Associate mapper but mapping should only return status and statusType if statusType matches any of {"O", "A", "P"} ?

As of now I'm doing custom default method in mapper like below

public AssociateMapper{
  Predicate<Status> status = (sts) -> null != sts &&null!=sts.getStatusType                                          
                                       && "O|A|P".contains(sts.getStatusType());    
 @Mappings({
            //some mappings   
          @Mapping(target = "statuses", expression = "java(associate.getStatuses().stream().filter(status).collect(Collectors.toList()))" )
          })
          Associate mapAssociate(Associate associate);
}

Is there any elegant way than this using mapStruct config itself?

1
what have you tried, where is the code and what didn't work out? - Naman
Updated the question with my trails - Naveen

1 Answers

2
votes

A more elegant way to achieve what you are trying to do would be to use a custom mapping between statuses.

In your case it would look like:

@Mapper
public AssociateMapper{

    Associate mapAssociate(Associate associate);

    default List<Status> mapStatuses(List<Status> statuses) {
        return statuses.stream()
            .filter(Objects::nonNull)
            .filter(status -> Objects.equals("O", status.getStatusType()) || Objects.equals("A", status.getStatusType()) || Objects.equals("P", status.getStatusType()))
            .collect(Collectors.toList());
    }
}

What you are doing in the expression can be part of a custom mapping for a list of Status(es). If there is a custom method that maps between List<Status> then MapStruct will use that one