I want to detect any duplicate object by its internal multiple properties, taken example:
class Person{
String name,
Integer age,
String address
//constructors
//getters setters
}
Now, out of above 3 parameters, I want to check duplication using 2 params, those are {name and age} I tried to achieve this using streams but seems there should be even simpler way using stream.
Current approach:
List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 10, "address1"));
personList.add(new Person("name2", 20, "address1"));
personList.add(new Person("name1", 10, "address2"));
personList.add(new Person("name3", 10, "address2"));
// Want to detect name1 and age 10 as a duplicate entry
Map<String, Map<Integer, List<Person>> nameAgePersonListMap = personList.stream()
.collect(Collectors.groupingBy(i -> i.getName(), Collectors.groupingBy(i -> i.getAge())));
// and later checking each element for size() > 1
Is there a further efficient way to determine duplicates in this use-case?
If the keys are not much of importance after this grouping and identifying the duplicates, you can perform the same as :
Map<List<?>, List<Person>> nameAgePersonListMap = personList.stream()
.collect(Collectors.groupingBy(i -> Arrays.asList(i.getName(), i.getAge())));
I said "much", because you can access the key
s still, just that the specific attribute would have to be cast into its type to retrieve it, for example entry -> (String)entry.getKey().get(0)
would give back the name used in the grouping.
So specifically useful when performing something like
personList.stream()
.collect(Collectors.groupingBy(i -> Arrays.asList(i.getName(), i.getAge())))
.entrySet().stream()
.filter(entry -> entry.getValue().size() > 1)
.map(Map.Entry::getValue)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With