'how to join two List of different signature type with a common property using Java stream()?

class ScannedCoupon{
    Long id;
    String scannedcode;
}
        
class WinnerCoupon{
    Long id;
    String winnercode;
    boolean won;
}
    
List<ScannedCoupon> scannedCouponList;
List<WinnerCoupon> winnerCouponList;

Here are my cases:

I do have two lists scannedCouponList with 30 items and winnerCouponList with 200. one them is code scanned by users and other is the list of winner. I want to update winnerCouponList if any of the ScannedCoupon's scannedcode is inside winnerCouponList.

is there any way to update the won property to true from winnerCouponList if any of the winnercode == scannedcode from scannedCouponList using java stream() ?

I do not want to use loops over and over again for 200 WinnerCoupon if any one of them is in scannedCouponList or not.



Solution 1:[1]

We loop around on winnerCouponList and at the same time for each winnerCoupon we check in scannedCoupon list have scannedCode == winnerCode. If yes, then we update the winnerCoupon.won = true. If no, we will continue in our loop until we found scannedCode == winnerCode or we reach the end of scannedCouponList

winnerCouponList.stream()
   .forEach(winnerCoupon -> {
       scannedCouponList.stream()
       .filter(scannedCoupon -> {
           return scannedCoupon.scannedcode.equals(winnerCoupon.winnercode);
       })
       .limit(1)
       .forEach(scannedCoupon -> winnerCoupon.won = true);
   });

Solution 2:[2]

winnerCouponList.stream()
    .filter(w -> scannedCouponList.stream()
    .anyMatch(s -> s.scannedcode.equals(w.winnercode)))
    .forEach(w -> w.setWon(true));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ash Anand
Solution 2 yulinxp