I have two objects that have two fields in common, code field and position field. I use two distinct lists, one of Object1 and another of Object2. Object2 was filtered before and had missing elements compared to Object1. I need to stream() on Object1 to compare code value and position value of objects that are still in the list of Object2 to keep them in the list of Object1.
Example:
//List<Object1> object1 :
object1.get(0) // code="VALUE1"; position=1; other fields...
object1.get(1) // code="VALUE2"; position=2; other fields...
object1.get(2) // code="VALUE3"; position=3; other fields...
//List<Object2> object2 :
object2.get(0) // code="VALUE2"; position=2; other fields...
object2.get(1) // code="VALUE3"; position=3; other fields...
object1 = object1.stream()...().collect(Collectors.toList()); // After object1 should have :
object1.get(0) // code="VALUE2"; position=2; other fields...
object1.get(1) // code="VALUE3"; position=3; other fields...
How can I do this with Java 8 Stream API?
map()is a good approach? If you want to compare similar objects based on their code and position, a better data structure than lists would be a map from the code and position to the objects. You could create a data type that just represents a code and position pair, and then use it to look up the objects with those values directly, assuming the code and position are unique and no two objects ever have the same values.