Reputation:
I have two object list, which have name as duplicate in both list. I need to remove all the duplicate value from list1 from list2.
Below is the scenario, class have name variable, with this variable need to check duplicate value from list1 and need to remove.
Class ObjectClass{
String name;
}
//this is first list have 3 objects
List<ObjectClass> list1= new ArrayList();
ObjectClass objectClassDataL1= new ObjectClass();
objectClassDataL1.setName("test");
list1.add(objectClassDataL1);
ObjectClass objectClassDataL2= new ObjectClass();
objectClassDataL2.setName("test2");
list1.add(objectClassDataL2);
ObjectClass objectClassDataL3= new ObjectClass();
objectClassDataL3.setName("test3");
list1.add(objectClassDataL3);
List<ObjectClass> list2= new ArrayList();
ObjectClass objectClassData1= new ObjectClass();
objectClassData1.setName("test");
list2.add(objectClassData1);
ObjectClass objectClassData2= new ObjectClass();
objectClassData2.setName("test3");
list2.add(objectClassData2);
I need to remove in list1 objects with the name
value as in list2.
For example here after removing the data from list1, list1 should contain only one object data.
Expected output:
list1 --> [Object('test2')]
list1 size is 1
Please suggest me in Java 8 with streams.
Upvotes: 4
Views: 527
Reputation: 31878
You can use Collection.removeIf
as:
list1.removeIf(a -> list2.stream().anyMatch(b -> a.getName().equals(b.getName())));
Upvotes: 2
Reputation: 131346
Please suggest me in JAVA 8 with stream,
Here you don't want to use stream as you want to modify the existing list1
.
What you can do is adding the names of list2
elements in a Set
and removing elements from list1
that are not contained in the Set
:
Set<String> namesInList2 = list2.stream().map(ObjectClass::getName).collect(toSet());
list1.removeIf(o -> namesInList2.contains(o.getName());
It makes things in two steps but it is clear and efficient enough.
Upvotes: 3