Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two arrays which both have data, what I want to do is to loop through each array and compare the data between the arrays one array is coming from the Post Method and another array has data from the database, so the comparison has to be done to check if the data is present in database to be updated else it should be inserted as a new a record.

What I have tried:

Below is my code snapshot

@Autowired
private OrderRepository orderRepository; 


public void process_data(String ordercode, List<Order> order) {
                
List<Order> orderList = new ArrayList<>(); 
List<Order> orderData = orderRepository.findOrder(ordercode);

// here is where I want to compare the data between two array lists of order and orderData
   using a for loop

for(var data : order) {  // here is only one array present how can I add the second array list so that I can compare the data present between the two array lists

}
Posted

1 solution

As I don't know what Order looks like, I'm going to make some assumptions in this answer. The big assumption I'm going to make is that you have an Integer id value in the class, which I can get using getId();. I'm also going to assume that the value is fixed - in other words, once the id has been applied, it's completely immutable and that's the value that would be saved to the database.

Now, if you really have to get your data like this, then I would be looking to use the filter capability in Java. Something like this:
Java
private Optional<Order> findOrder(List<Order> orders, Order order) {
  return orders.stream().filter(f -> f.getId() == order.getId()).findAny();
}
Then you would call this inside your loop like this
Java
Optional<Order> foundOrder = findOrder(orderData, data);
if (foundData.isPresent()) {
  // Do whatever you need to with this missing record.
}
Without more information, I can't really give you a more optimised solution.
 
Share this answer
 
Comments
Office Systems 11-Mar-24 4:49am    
Thanks so much @Pete O'Hanlon this works fine 👍
Pete O'Hanlon 11-Mar-24 6:58am    
That's great. Thanks for letting me know.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900