Find Duplicate Objects Based on Property in Java

Extract duplicate objects from a List in Java 8

If you could implement equals and hashCode on Person you could then use a counting down-stream collector of the groupingBy to get distinct elements that have been duplicated.

List<Person> duplicates = personList.stream()
.collect(groupingBy(identity(), counting()))
.entrySet().stream()
.filter(n -> n.getValue() > 1)
.map(n -> n.getKey())
.collect(toList());

If you would like to keep a list of sequential repeated elements you can then expand this out using Collections.nCopies to expand it back out. This method will ensure repeated elements are ordered together.

List<Person> duplicates = personList.stream()
.collect(groupingBy(identity(), counting()))
.entrySet().stream()
.filter(n -> n.getValue() > 1)
.flatMap(n -> nCopies(n.getValue().intValue(), n.getKey()).stream())
.collect(toList());

How to find duplicates in a list of list of objects in java

Actually, you have:

List<List<String>> compositeKeyValues;

Lists are equal if they have the same elements in the same order - like your example.

Finding duplicate inner Lists is no different finding duplicates of other simpler types.

Here's one way:

List<List<String>> duplicates = compositeKeyValues.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue().intValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());

This code will work even if you leave the type of the List as List<Object>, except the result would also have type List<Object>. However, it's recommended, and more useful, to use a more specific type List<List<String>>.

segregate duplicates and non duplicates from a list of objects based on property on multiple property in java 8

You can group the elements depending on adding to your set returns true or false:

public  static Map<String ,List<Asset>> execute2() throws IOException {

List<Asset> assetList=new ArrayList<>();
Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

assetList.add(asset1);
assetList.add(asset2);
assetList.add(asset3);
assetList.add(asset4);
assetList.add(asset5);
assetList.add(asset6);

Set<Asset> set=new HashSet<>();
return assetList.stream().collect(Collectors.groupingBy(x -> set.add(x) ? "nonDuplicateList" : "duplicate"));
}


Related Topics



Leave a reply



Submit