Compare two list of maps in java

Often, we're faced with situations, in which we have to merge multiple Map instances into a single one, and guarantee that key duplicates are handled properly. In most imperative programming languages, including Java, this is a trivial problem.

Comparing 2 list of objects in C# using IEquatable

With a few variables to store state, and a couple of nested loops, and several if-else statements, even people new to Java could program a solution within minutes. Yet, is this the best way to do it? Though guaranteed to work, such solutions could easily get out of hand and become incomprehensible at a later point of development.

Java 8 brought with itself the concept of streamsand opened the door of possibilities for solving such problems in a declarative functional manner.

Moreover, it reduced the need of having to store intermediate state in variables, eliminating the possibility of some other code corrupting that state at runtime. The key of each map is the ID of a certain user, and the value is the number of user visits to given part of the system.

We want to merge those two maps using streams, such that where the same key user ID appears in both, we want to take the sum total of user visits across all parts of the system. First, we need to combine all maps into a unified Stream. There are multiple ways of doing this but my preferred one is using Stream. Then, comes the collecting part.

Collecting in Java 8 streams is a final operation.

compare two list of maps in java

It takes a given stream, applies all transformations mostly from map, filter, etc and outputs an instance of a common Java colelction type: List, Set, Map, etc. Most common collectors reside in the java.

Collectors factory class. I will use Collectors. The default implementation of Collectors. Upon iterating over the stream, both lambda parameters get called and passed the current stream entry as an input parameter.

The first lambda is supposed to extract and return a key, whereas the second lambda is supposed to extract and return a value from the same entry. This key-value pair would then serve for creating a new entry in the final map. What happens here is rather straightforward. The collector would use the keys and values of the existing maps to create entries in the resulting map.

Of course, trying to merge maps with duplicate keys will result in an exception. A little known version of the same method accepts athird lambda parameter, known as the "merger".

This lambda function will be called every time duplicate keys are detected. The two possible values are passed as parameters, and it is left to the logic in the function, to decide what the ultimate value will be.

This third lambda makes solving our problem easy, and in a very elegant manner:. February 06, Last Updated: February 06, The Solution First, we need to combine all maps into a unified Stream.

Written by Preslav Rachev. Sponsored by. Awesome Job. See All Jobs.GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community. Already on GitHub? Sign in to your account. This issue was originally filed by le Added Area-LibraryTriaged labels.

This comment was originally written by ggirou. Set owner to lrhn. Removed Type-Defect label. Added Type-EnhancementAccepted labels.

This comment was originally written by seaneagan.

compare two list of maps in java

Here's some pseudocode:. On further consideration, I'm not sure it's really a good idea to identify two mutable sets just because they currently have the same elements. One might be preserving iteration order, the other not, and if they iterate elements in different orders, are they really the same Set object.

They represent the same mathematical set, but mathematical equalities aren't always the correct computational equality. I think I'd rather have a.

compare two list of maps in java

I believe Object will get a hashCode function, making all objects hashable. That's a further complication. If sets are equal based only on elements, we need to compute a hash value for a Set that is independent of the order that elements are iterated in.

That is likely to make for a lousy hash value. It also makes either the hash value slow to compute, or the class needs to cache and update the hash value based on single element changes. Caching and updating a hash value is an unnecessary overhead if you don't use it. It's possible to have special versions that do that, but then they also need to have a strategy for computing the hashValue.

This comment was originally written by jjinux It's pretty surprising to me that [1, 2, 3]! If people want something fast, they can just use the identical method. Lists are simple relative to Set and Map because the ordering is integral to the value. To be really safe, the hashCode of a collection with equality should be calculated every time it's queried because, since it must depend on the hashCode of the values, and the values might change even if the collection doesn't at least for List and Map values, but Set and Map keys aren't allowed to change.

That makes hashCode an expensive operation.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 want to check if two maps are exactly the same without knowing their depth. Instead of using recursion can I compare the output of the toString called on each map?

Or is there a simpler way to compare the maps? You should use the equals method since this is implemented to perform the comparison you want. Additionally, as Teepeemm pointed out, toString is affected by order of elements basically iterator return order hence is not guaranteed to provide the same output for 2 different maps especially if we compare two different maps.

The default java classes do so, but a custom map class needs to be examined to verify expected behavior. Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.

This ensures that the equals method works properly across different implementations of the Map interface. Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap :.

As long as you override equals on each key and value contained in the map, then m1. The same result can be obtained also by comparing toString of each map as you suggested, but using equals is a more intuitive approach. May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays. More details about this see here. Learn more.

Difference between Set, List and Map in Java - Interview question

Comparing two maps Ask Question. Asked 5 years, 9 months ago. Active 2 years, 4 months ago. Viewed 91k times. Using toString would fail if the map entries came out in different orders, which is entirely possible.

Why do you hate it? In any case, I initially thought that OP was talking about HashMap instances because my reading skills are terrible, but then realized that even for those what I said wasn't true. It was after that that I realized that OP just has Map instances. In any case, you are correct. Active Oldest Votes. Quick Answer You should use the equals method since this is implemented to perform the comparison you want.

Implementation in Java Source java. AbstractMap Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. JonyD 1 1 gold badge 15 15 silver badges 28 28 bronze badges.

Menios Menios Kick Buttowski What do you mean? It should be emphasized that even if both maps have the same type, i.The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.

Anitha Kuchana wrote: thank you for your answer. Forum: Java in General. How we compare two maps in java. Anitha Kuchana. My data present in list. That list is a value of MAP. Now i want to compare list values.

How we compare list values of Map data structure. Please any one help me?

comparing two Maps in Java (finding missing elements)

Raghav Viswanathan. I like Hello Anitha, Could you please post a code sample of the objects that you have to compare. The post doesnt seem to be that clear. Thanks, Raghav V. Junilu Lacar. This is a common anti-pattern that I have the misfortune to see too many times. A map that contains maps that map object properties as key-value pairs.

It's a very bad practice and rather than try to figure out the answer to your original question, I suggest you choose a different data structure. Java is an object-oriented language, so what you should have is, at the least, a List of objects that encapsulate the values of 'code', 'name', etc. Then you can use the built-in List methods to check if an element of one List has an equivalent element in another List. And how to convert from map into list?

And solution for the above situation?

How to compare two ArrayLists in Java

You'll have to ShowSomeEffort and give it your best shot to do it yourself. Since you're using Hibernate, you should read up on Object-Relational Mapping concepts and how to map translate relational data into objects. Hibernate can actually do a lot of the heavy lifting for you here. Edit: missed the fact that you asked for examples. Good luck. Winston Gutkowski. Iterate through the Map "values", and then iterate through each value in its list, and add them to a standard List.

If you want better advice than that, then you'll have to give us a LOT more information about what it is you want to do.Learn to compare two hashmaps in Java by keys, values and key-value pairs.

Also learn to compare while allowing or restricting duplicate values. By default, HashMap. It means both hashmap instances must have exactly same key-value pairs and both must be of same size. If we want to compare hashmaps by keys i.

It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set. It returns true if the two sets have the same size, and every element of the specified set is contained in another set. We may be interested in finding out what extra keys first hashmap has than second hashmap.

So get this difference, first do a union of keys from both hashmaps, and then remove all keys present in first hashmap.

If we want to compare hashmaps by values i. Please note that HashMap allows duplicate values, so decide if you want to compare hashmaps with duplicate or without duplicate values. Add all values from HashMap. Now compare both arraylists for equality. If you want to remove duplicate values before comparing the hashmaps, the add all values into a HashSet which automatically ignores duplicate values.

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter. Looks like you copied 3. I think you intended to use HashSet in 3. The program displays student record of various universities First program needs to know how many universities records you wish to enter Secondly program takes the input for each university i.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.

compare two list of maps in java

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.The best ideas are the crazy ones.

If you have a crazy idea and it works, it's really valuable. Anitha Kuchana wrote: thank you for your answer. Forum: Java in General. How we compare two maps in java. Anitha Kuchana. My data present in list. That list is a value of MAP. Now i want to compare list values. How we compare list values of Map data structure. Please any one help me? Raghav Viswanathan. I like Hello Anitha, Could you please post a code sample of the objects that you have to compare.

The post doesnt seem to be that clear. Thanks, Raghav V. Junilu Lacar. This is a common anti-pattern that I have the misfortune to see too many times. A map that contains maps that map object properties as key-value pairs. It's a very bad practice and rather than try to figure out the answer to your original question, I suggest you choose a different data structure. Java is an object-oriented language, so what you should have is, at the least, a List of objects that encapsulate the values of 'code', 'name', etc.

Then you can use the built-in List methods to check if an element of one List has an equivalent element in another List.

And how to convert from map into list? And solution for the above situation? You'll have to ShowSomeEffort and give it your best shot to do it yourself. Since you're using Hibernate, you should read up on Object-Relational Mapping concepts and how to map translate relational data into objects.


comments

Leave a Reply

Your email address will not be published. Required fields are marked *

1 2