Skip to content
Advertisement

What is the right way to compare the List of HashMap in Java using streams

I want to compare two List of HashMaps in Java. I want to understand a way to compare them using lambda expressions and not with a nested for loop.

Two List of HashMaps :

  1. productDetailsFromInputData;

Sample Data :

JavaScript
  1. productDetailsFromApplication;

Sample Data :

JavaScript

Logic : I want to loop through the productDetailsFromInputData List and fetch the ProductName Value for each hashmap, check if the value exists in any of the hashmaps present in productDetailsFromApplication List. If not, mark the result as failed.

If the ProductName Exists as value in any one of the hashmap of productDetailsFromApplication List, fetch the Perpetual and Quantity values from that hashmap and compare it with hashmap in productDetailsFromInputData list.

I have tried below approach as of now :

JavaScript

I want to understand if there is a way to remove the first for loop as well. As I am fairly new to using lambda and streams, how can I optimize it.

Also I would like to know a way to return boolean value if the code reaches the LOGGER.error part where I have currently added assertions to mark the failures.

If there is an existing Stack-overflow question that covers the solution to this problem, feel free to guide me there.

Advertisement

Answer

From your statement, I understand you want to return false instead of running the Assert.fail. The way of doing this by only using Streams is:

JavaScript

Notice I am mapping the failures to true, that’s because anyMatch would look for any true value. We then negate that with the ! in the return.

If you want to keep the LOGGER verbosity, you can probably do something like:

JavaScript

However, I would suggest not to use only Streams and first converting productDetailsFromApplication to a Map so it is faster to find the match:

JavaScript

This would stop on the first failure and not count all of them. If you could benefit from counting the failures and/or logging all of them, you could use .filter(b -> b).count() instead of .anyMatch(b -> b).

JavaScript

EDIT: You can actually move the anyMatch statement further up replacing the first map, but having it at the bottom let’s you change it easily to other uses such as the count if needed.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement