Java compare two lists of objects and get differences

Comment 4. Comparing the content of List s against some condition is a common use case to handle in many business scenarios. This comparison can be broadly classified as:. Now, developing these use cases is very easy in Java 7 with relatively few lines of code. The following is an example where we are comparing two Lists in Java 7 and checking if any element from List 1 exists in List 2.

Now let us develop all the above use cases in Java 8. It is recommended to check the following articles if you are not familiar with the Stream API.

java compare two lists of objects and get differences

Example of different kinds of streams in Java 8. Example of different kinds of streams in Java 8 [Part 2]. Given a stream of objects, many-a-times, we need to check whether objects in the given stream match some specific criteria. Instead of writing logic for iterating over the stream elements and checking whether each object matches the criteria, Java 8 Streams allow declarative matching of objects in the stream.

We need to define a Predicate instance with the comparison logic and provide this Predicate as an input to the matching methods. Then, Java 8 processes the matching function internally and provides you with the result whether a match for the condition was found or not. The element of the stream is iterated for this Predicate. Now let us check some examples of these methods. Now we will define some predicates for checking some conditions that will be used in these methods. The output of the program is:.

We can collect all the elements matching the given Predicate to some Collection. Let us rewrite the program in Java 8 using these matching methods. Published at DZone with permission of Arpan Das. See the original article here. Over a million developers have joined DZone.

java compare two lists of objects and get differences

Let's be friends:. Java 8. How to Compare List Objects in Java 7 vs.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time.

ヨコハマ BluEarth AE-01F 175/65R14【店頭取付限定】 2019年製 工賃込み価格 お取り寄せ商品 4本セット 夏タイヤ 納期3~4日程度 タイヤ単品 新品

Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Is there a Java utility library that is analogous to the Unix program diff, but for Objects? I'm looking for something that can compare two objects of the same type and generate a data structure that represents the differences between them and can recursively compare differences in instance variables.

I'm not looking for a Java implementation of a text diff. I'm also not looking for help with how to use reflection to do this. The application I'm maintaining has a fragile implementation of this functionality that had some poor design choices and that needs to be rewritten, but it would be even better if we could use something off the shelf. After comparison, the utility would tell me that "prop1" is different between the two objects and "prop2" is the same.

I think it's most natural for DiffDataStructure to be a tree, but I'm not going to be picky if the code is reliable. Might be a little late, but I was in the same situation like you and ended up creating my own library for exactly your use-case. Since I was forced to come up with a solution myself, I decided to release it on Github, to spare others the hard work.

In addition you can get Snapshot of any graph object. Javers has JSON serializers and deserializers to snapshot, and changes so you can easily save them in database. With this library you can easily implement a module for auditing. It returns the difference as a List of deltas. The GraphComparator also permits you to merge apply the deltas as well. This code only has dependencies on the JDK, no other libraries.

All the Javers library has support to only Java 7, I was in a situation since I want this to be used for a Java 6 project so I happened to take the source and change in a way it works for Java 6 below is the github code. You could also take a look at the solution from Apache.When comparing two operands.

It is used to check whether two operands are equal or not. It is good to use compareTo when you need to compare two String literals. When using the compare method, it is ideal to use this on Integer types. They are used in a programming flow to check if certain criteria match or are similar, such as:. This is for example, the recommended method of comparing Strings. Alnitak, A reference equals is very useful for primitive data types such as int s but soon becomes a problem when comparing more complex objects.

Even in our example above we had to use. Another useful comparison method is compareTowhich performs a lexicographical comparison of two objects. It is specifically useful for sorting comparisons passed to it as the comparison is done by comparing a range of String characters and or Double values.

For example, String abc is -1 when compared to String abd because the c is lexicographically one less than d. Therefore two strings with the same value would return a 0 as they are the same and have 0 differences.

The order of this check is therefore extremely important. The compare is another method that is useful for comparing objects, it is different to compareTo in that it can sort multiple elements and returns the value instead of modifying the original class. Comparable and Comparator are both Interfaces and can both be used to sort collections of elements. Notify me of follow-up comments by email. Notify me of new posts by email.

When to use equals in Java This method is best used when comparing String types. When to use compareTo in Java It is good to use compareTo when you need to compare two String literals. When to use compare in Java When using the compare method, it is ideal to use this on Integer types. Like this: Like Loading Tags: Java.

Leave a Reply Cancel reply Your email address will not be published.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I have two lists. They contain objects of different types, but both types contain id and name, and id is what I am comparing on. List one is fetched from DB, and list two is sent from frontend.

What I need to do is loop through them and find which list item is newly added and which one was deleted. List two is filled with that type of objects. This works, I have tested it. Are there better solutions? I was thinking of using Sets so I can compare them, Is there a downside to that? First thing first, I would use some type adapter or extend the different types from one common class and override the equals method so you can match them by id and name.

Secondly, this is very easy operations on sets you could use set's but list are fine too. Otherwise, all collections implementing Collection Java Docs also has removeAll method, which you can use. This is basically your solution but implemented using streams, which will make your code shorter and easer to read.

You are always better off storing the IDs of one list into a Set allowing efficient lookup, then process the other list utilizing the Set. Since swapping the two lists requires the helper method to be independent from the element types, it expects functions for accessing the id property, which can be specified via method references. Then, a function describing the result element is required, which is an identity function in one case just getting the NamedDTO and a lambda expression constructing a NamedDTO from SomeObject in the other.

The operation itself is as straight-forward as described above, iterate over one list, map to the id and collect into a Setthen, iterate over the other list, keep only elements whose id is not in the set, map to the result type and collect into a List.

java compare two lists of objects and get differences

If these id's are unique, you could put them in a HashSet and find thus the ids you are interested in:. I also assume that if an element is contained in the uiSetbut not in dbSet is has been added and the other way around. Learn more.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service.

Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up. I have two lists of Person objects. I need to compare the lists to determine if items in list1 exist in list2 and vice versa. This is not a straight equals scenario as the objects are not the same, but may have identical field values. It is those values that I need to compare. In my real-world application, however, both lists have over 30, items and this is very time-consuming.

Is there a better way to perform this comparison? I would want this to work both ways as well, so if there are items in newPeople that were not in originalPeopleI would want that list as well. More efficient data structures exist:. To be to search efficiently, use a hashset instead of a list. However, to be able to use a hashset efficiently, it is required that the objects you put in it have appropriate implementation of hashCode and equals methods.

See the official tutorial on the Object classespecially the sections on the equals and hashCode methods. Note that IDEs like IntelliJ and Eclipse can generate these methods for you easily they are boring to write by hand, and usually there's little reason to do so. With correct implementation of the equals and hashCode methods, for example as in the other answer by Teddy, your main program could be reduced to this:.

You could do it inside the same filter like I've shown below. For that you need another else condition which increases the cyclomatic complexity. Lists are linear in terms of performance. You are iterating original list, which cannot be avoided.

But, for each item in original you are iterating the new list looking for a match. This is bad for performance. You should just add all the new data to a HashSet. Then iterate the original list and check if the HashSet contains that pair.

Comparing Objects in Java

To use a HashSet, the main thing is the hash function. If the person class can be made to have a hashCode only relating the firstName and the lastName, then you can go with that option.

If not just use a Pair. Its a standard tuple, and one should be available in some of the collections already in your project classpath. If those lists are not immutables then i would perfer to sort the lists and then traverse.

Using stream you will always end up with complexicity of. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered. Determine if 2 lists with similar objects contain a partial duplicate [closed] Ask Question.Learn to compare two arraylists in Java with simple examples.

We will first test if two arraylists are equal or not. If both lists are not equal, we will find the difference between lists. The difference in list is equals to another third list which contains either additional elements or missing elements.

If two arraylists are not equal and we want to find what are additional elements in first list in comparison to second list then we can use this method.

It uses removeAll method which removes all elements of second list from first list. It leaves only additonal elements in first list. To get the missing elements in first list, which are present in second list, we can reverse the above example. Here we can remove all elements of first list from second list using removeAll method. To find common elements in two arraylistsuse List.

This method retains only the elements in this list that are contained in the specified arraylist passed as method argument. Above example will work good in Java 8 as well. A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter. Hi Lokesh, For finding the common elements, does retainAll method goes thru the entire list? Is this the best approach to find the common elements or is there any other approach which is better than retainAll and contains?

Thank you, bkk. I have 2 arraylist to compare and pass if values are matching. One of the arraylist contains the values with some textonce i remove the extra content, i can compare using your method. Please break the code in multiple lines.

Execute one method at a time and assign the result to a variable. You are doing so much in single line. Then put breakpoints and debug.Java equals method of List interface compares the specified object with the list for equality.

It overrides the equals method of Object class. This method accepts an object to be compared for equality with the list. It returns true if the specified object is equal to the list, else returns false. In the following example, we have create two ArrayList firstList and secondList. Comparing both list by using equals method, it returns true. We have added another element in the secondList to create a difference between firstList and secondList. Now, if we perform comparison, it returns false.

Java removeAll method of ArrayList class is used to remove all elements from the list that are contained in the specified collection. This method accepts Collection as a parameter containing elements to be removed from this list. It returns true if this list changed as a result of the call. In the following example, we have created two ArrayList firstList and secondList.

The removeAll method removes all the elements of the firstList because the same elements are also present in the secondList, except Papaya. So, Papaya is the missing element in the firstList.

Hence, it returns Papaya. The method returns an empty list [] if both the list have same elements. Let's see another example of removeAll method that returns the elements from firstList which are not present is the secondList. Java retainAll method of ArrayList class retains only the elements of the list that are contained in other list also. This method accepts a Collection as a parameter that contains elements to be retained in the list. In this example, we have created two ArrayList firstList and secondList by using the asList method of the Arrays class.

The asList method returns a list view of the specified array. Java ArrayList. This method parses an element whose presence in the list is to be checked. It returns true if the element is matched, else returns false. We have compared these ArrayList using contains method.

If the elements of firstList match with the elements of the secondList, it return Yes and stores this value into thirdList. Similarly, if the element does not match, it return No. Java contentEquals method compares the String with the StringBuffer and returns a boolean value. It belongs to String class.

This method accepts StringBuffer as a parameter to compare against the String. It returns true if the String represents the same sequence of characters as the specified StringBuffer, else returns false. We have created a static method compareList which parses two ArrayList ls1 and ls2 as an argument and returns a boolean value. The method converts a list into String. The contentEquals method compares the String to the specified StringBuffer. We have added another element in the secondList to create the difference between both lists and again call the compareList method, which returns false.

Java Stream is an interface. It belong to java. It provides a filter method to filter stream elements on the basis of given elements.


Comments on “Java compare two lists of objects and get differences