Java find Object which not containing in List of object

Tags: , ,



I wondering is there any way to filter object array with another object array. Its is to hard to explain but ill try my best

this is my first entity

public class MDynamicFieldTypes implements Serializable {
    private Long id;
    @Enumerated(EnumType.STRING)
    private TDynamicFieldCategories category;
    private String icon;
    private String code;
    private String text;

}

this is second entity

public class DynamicFields implements Serializable {

    private Long id;
    private Instant createdDate;
    private Instant lastModifiedDate;
    private String value;
    private UserProfile createdByUser;
    private UserProfile lastModifiedByUser;
    private Project project;
    private EntityProfile entityProfile;
    private UserProfile userProfile;
    private MDynamicFieldTypes type;
  
}

i have two list of this each entities Like this

List<MDynamicFieldTypes> dynamicFieldTypes;
List<DynamicFields> dynamicFields;

And I need to get MDynamicFieldTypes list which not containing in dynamicFields->type List and add fake object to which not containing in the dynamicFields List

as the example

First list like this

List<MDynamicFieldTypes> dynamicFieldTypes = [{id=1,category="A",code=a1,text="ccc"},
{id=2,category="B",code=a2,text="bbbb"},
{id=3,category="C",code=a3,text="cccc"},
{id=4,category="C",code=a4,text="cccc"},
];

Second one like this

List<DynamicFields> dynamicFields=[{id=1,value="xxx",type={id=1,category="A",code=a1,text=b},{id=2,value="yyy";type={id=3,category="C",code=a3,text=b},];

i need get as the result following List

List <MDynamicFieldTypes> notContaing =[{id=2,category="B",code=a2,text="bbbb"},{id=4,category="C",code=a4,text="cccc"}];

Answer

Here is a two step solution

First create a set of all existing types in the dynamicFields list

Set<MDynamicFieldTypes> existing = dynamicFields.stream().map( f -> { return f.type; } ).collect(Collectors.toSet());

Then use that set to filter out any non-existing type in the dynamicFieldTypes list

List<MDynamicFieldTypes> missing = dynamicFieldTypes.stream().filter( type -> { 
  return !existing.contains(type);
}).collect(Collectors.toList());


Source: stackoverflow