Skip to content
Advertisement

How create a list of an object from two different types of lists

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?

Advertisement

Answer

If I understood your description correctly the following should do it:

public static void main (String[] args) {
    List<Object1> object1 = new ArrayList<>();
    object1.add(new Object1("1", 1));
    object1.add(new Object1("2", 2));
    object1.add(new Object1("3", 3));
    object1.add(new Object1("4", 4));
    object1.add(new Object1("5", 5));

    List<Object2> object2 = new ArrayList<>();
    object2.add(new Object2("1", 1));
    object2.add(new Object2("2", 2));
    object2.add(new Object2("5", 5));

    List<Object1> filteredObject1 = object1.stream()
            .filter(o1 -> object2.stream().anyMatch(o2 -> o2.getCode().equals(o1.getCode()) && o2.getPosition() == o1.getPosition()))
                    .collect(Collectors.toList());

    System.out.println(filteredObject1);
}

It keeps in object1 the Object1 instances that have the same code and position of an Object2 instance in object2.

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