Filter list by properties of a field of the list object

skidalgo :

Given all TypeA instances in a List<TypeA> have an instance of SubTypeB set in the superTypeB field, I need to filter out duplicate TypeA instances from the list, where a duplicate means the values of propertyA and propertyB from the SubTypeB both match. Is there a way to do this with the Java 8 stream API?

public class TypeA {
  private SuperTypeB superTypeB;
  public SuperTypeB getSuperTypeB(){ return superTypeB; }
}

public class SuperTypeB {
  private String propertyX;
}

public class SubTypeB extends SuperTypeB {
  private String propertyA;
  private String propertyB;
  public String getPropertyA(){ return propertyA; }
  public String getPropertyB(){ return propertyB; }
}
Naman :

You need to be sure to not map before you filter to collect to the same type. Using a distinctByKey utility, you can further choose to collect to a List as :

List<TypeA> filteredTypeAs = typeAList.stream()
        .filter(distinctByKey(s -> {
            SubTypeB subTypeB = (SubTypeB) s.getSuperTypeB();
            return Arrays.asList(subTypeB.getPropertyA(), subTypeB.getPropertyB());
        }))
        .collect(Collectors.toList());

Note: This relies on the assumption as stated in the question that all the subtypes are possible to cast without an instanceof check.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=335315&siteId=1