Search code examples
javajava-stream

How to compare a property of an object in a list with another property of a similar object in different list using java Sreams using Java 11


Please consider 2 Classes:

Class Object1 {
  int id;
  String test;
  ...
}

Class Object2 {
  int id;
  Boolean flag;
  ...
}

Object1 and Object2 are not equal.

Now, please consider I have a list of Object1 and Object2 as follows:

List<Object1>
Set<Object2>

Problem statement: I need to write a filter condition in the Java streams where

Object1.getId() == Object2.getId().

Can you please guide me here.

Edit: I want to filter List.

Do you want to compare elements pairwise or check for inclusion anywhere in the second collection? I want to check for inclusion anywhere in the second collection.


Solution

  • You can use Java 8 Lambda.

    1. Convert set to stream.
    2. Use stream filter
    3. Use containsKey to compare
    4. Collect it to List.

    Object1 List and Object2 Set

    
    List<Object1> object1List = ... 
    Set<Object2> object2Set = ... 
    
    

    Filter Object1

    
    Map<Integer, Object2> object2Map = object2Set.stream()
        .collect(Collectors.toMap(Object2::getId, Function.identity()));
    
    List<Object1> result = object1List.stream()
        .filter(a -> object2Map.containsKey(a.getId()))
        .collect(Collectors.toList());