Find duplicate objects based on property in Java

remove duplicates from a list of objects based on property in java 8
java 8 find duplicates in list of objects
remove duplicates from a list of objects based on property in java 7
java stream find duplicates by property
how to find duplicate objects in a list in java
java remove duplicates from list of objects
remove duplicates from list java 8
remove duplicate custom objects from arraylist in java

This is my object structure.

List<Customer> customerSelection = new ArrayList<Customer>();
    Customer c1 = new Customer();
    Customer c2 = new Customer();

    c1.setName("Syed");
    c2.setName("Syed");
    Map<String,String> locationList1 = new HashMap<String,String>();
    Map<String,String> locationList2 = new HashMap<String,String>();
    locationList1.put("DXB", "Dubai");
    locationList1.put("AUH", "Abudhabi");

    locationList2.put("DXB", "Dubai");
    locationList2.put("BAH", "Bahrain");

    c1.setLocationList(locationList1);
    c2.setLocationList(locationList2);

    customerSelection.add(c1);
    customerSelection.add(c2);

Here I want to validate if a customer is having preferred duplicate location, I should throw an error message. Any ideas on optimized solution?

Here Syed is having dubai as as location in location list which is invalid.

You can check the locations do not overlap at time of adding:

safeAdd(customerSelection, c2);

Using Collections.disjoint which returns true iff the two specified collections have no elements in common.

private static void safeAdd(List<Customer> customerSelection, Customer newCustomer) {
    if (customerSelection
            .stream()
            // look at all the users with matching name
            .filter(customer -> customer.name.equals(newCustomer.name))
            // ensure all of them have no location overlap with the new customer
            .allMatch(customer -> Collections.disjoint(customer.locationList.keySet(), newCustomer.locationList.keySet()))) {
        customerSelection.add(newCustomer);
    } else {
        throw new RuntimeException("Cannot add customer, customer with this name exists with this location");
    }
}

Or Java 7:

private static void safeAdd(List<Customer> customerSelection, Customer newCustomer) {
    for (Customer customer : customerSelection) {
        if (customer.name.equals(newCustomer.name) &&
                !Collections.disjoint(customer.locationList.keySet(), newCustomer.locationList.keySet())) {
            throw new RuntimeException("Cannot add customer, customer with this name exists with this location");
        }
    }
    customerSelection.add(newCustomer);
}

Removing duplicates from the list of objects based on more than one , In Java Stream perform group by operation based on that we can find duplicate object from collection or list. java.util.List<String> list = Arrays. Do you want to identify duplicates elements from Java List? The method add of set returns a boolean whether a value already exists (true if it does not exist, false if it already exists, see Set documentation).

You can iterate through list and check whether HashMap has same key present in other Customer's locationList.

for(int i=0; i<customerSelection.size()-1;i++){
   for(int j=0;j<customerSelection.size()-1;j++){
     if(j!=i){
   HashMap map   =    customerSelection.get(i).getLocationList();
   for(Map.Entry<> entry: map.entrySet()){
      if(customerSelection.get(j).getLocationList().containsKey(entry.getValue())) {
        THROW ERROR               
             }
      }

      }
   }

}

Java Find duplicate objects in list, remove duplicates from a list of objects based on property in java 7 java 8 find duplicates in list of objects how to find duplicate objects in a list in java java 8 filter� JavaScript : find an object in array based on object's property (and learn about the "find" function) Published on March 20, 2017 March 20, 2017 • 314 Likes • 48 Comments Report this post

please have a look here too

    public static void main(String[] args) {
        List<Customer> customerSelection = new NonDuplicateLocationsList();
        Customer c1 = new Customer();
        Customer c2 = new Customer();

        c1.setName("Syed");
        c2.setName("Syed");
        Map<String,String> locationList1 = new HashMap<String,String>();
        Map<String,String> locationList2 = new HashMap<String,String>();
        locationList1.put("DXB", "Dubai");
        locationList1.put("AUH", "Abudhabi");

        locationList2.put("DXB", "Dubai");
        locationList2.put("BAH", "Bahrain");

        c1.setLocations(locationList1);
        c2.setLocations(locationList2);

        customerSelection.add(c1);
        customerSelection.add(c2);
    }
}
class Customer {
    Map<String, String> locations;
    String name;

    public Map<String, String> getLocations() {
        return locations;
    }

    public void setLocations(Map<String, String> locations) {
        this.locations = locations;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class NonDuplicateLocationsList extends ArrayList<Customer> {


    @Override
    public boolean add(final Customer customer) {


        for (Customer customer1 : this) {
            if (Maps.difference(customer1.getLocations(),customer.getLocations()).entriesInCommon().size() > 0) {
                throw new RuntimeException("Has Location duplicates");
            }

        }
        return super.add(customer);
    }
}

Finding duplicated objects by two properties, Learn to find distinct objects from a stream by comparing multiple fields or each object is distinct by comparing multiple fields or properties in Java 8. pass multiple key extractors (fields on which we want to filter the duplicates). In given example, we are finding all records having distinct ids and name . Remove duplicate custom objects from arraylist in java March 24, 2017 Java Basic No Comments Java Developer Zone Recently i write one post related to remove duplicate object from Array , But in that example i used String Example and String is immutable object and too much feet for any collection.

Java 8 stream distinct by multiple fields, a collection. Let's learn how to find distinct elements with Java stream API. Table of Contents Filter Distinct Elements Filter Distinct Elements by Object Attribute/Property Get collection without duplicate i.e. distinct only How to filter based on distinct fname and lname from the above example? Reply. We can remove the duplicate elements from a list in following 2 different ways. Removing Duplicates by assigning List to TreeSet : Preparing a list containing duplicate Department objects, and remove those duplicate departments using Java8 stream. Here to remove the duplicate elements, by assigning a list to TreeSet. As TreeSet doesn’t allow

Java Stream Distinct Examples, From Java 8 on with the inclusion of Streams we have a new API to process data elements of a list based on the equals() method of the Object class. You can find the latest version of the Eclipse Collections library in the� JFilter is a simple and high performance open source library to query collection of Java beans. Key features. Support of collection (java.util.Collection, java.util.Map and Array) properties. Support of collection inside collection of any depth. Support of inner queries. Support of parameterized queries. Can filter 1 million records in few 100 ms.

DistinctBy in Java Stream API, Given a stream containing some elements, the task is to find the duplicate elements in method of Collectors class in Java groups the objects by some property. The purpose of this article is to share with you the best ways to remove duplicate objects from JavaScript Array based on specific property/key. We will also analyze their performance in terms of execution time for different lengths of the array. If you want to learn how to remove duplicate PRIMITIVE values from JavaScript array check this article.

Comments
  • Why do you need a Map instead of a List for the locations?
  • @ayrton, this is an existing object structure, so I didn't bother about it which is having location id and location name.
  • I am not fully understand what you are asking. You don't want to duplicate key and value or you don't want to duplicate keys, or you don't want to duplicate values?
  • @SaidAlır, the customerSelection list will have duplicate objects based on customer name. But customer should not give duplicate preferred locations.
  • So, requirement is, they can have different names and same location, or same name and different locations, but never same name and same location?
  • ::( I'm having JDK as 1.7, so I can't use 1.8.., If possible please let me know in 1.7
  • I'm sure you can work it out. Just use a for loop. Collections.disjoint is doing the hard work.
  • Thanks Weston. But how to call this method? while iteration of customerSelection? as I see you are passing safeAdd(customerSelection, c2); as hardcoded, because at the time of runtime, there can be multiple customers,right?
  • We'll you call safeadd rather than add. I don't really understand what you don't understand.
  • My point is why are we passing c2 in this method as hardcoded.. safeAdd(customerSelection, c2); we just have to iterate the list and validate it right? Please correct me if Im wrong
  • for(Map.Entry<> entry: map.entrySet()){ .. This has compilation problem
  • Use Map.Entry<String,String>
  • So I create a new class extended from Araylist, override add method and check all the stuff there, so that no one can add duplicate items there
  • The locationlist is a map object, but not list object. Please check it again.