3

I have a DTO that looks like -

@Getter
@Builder
class Person{
    private String id;
    private String name;
    private Integer age;
}

A new arraylist is created as -

List<Person> persons = new ArrayList<Person>();
persons.add(Person.builder().id("001").name("alpha").build());
persons.add(Person.builder().id("002").name("beta").build());
persons.add(Person.builder().id("003").name("gamma").build());

another list exists as -

List<Person> ages = new ArrayList<Person>();
ages.add(Person.builder().id("001").age(25).build());
ages.add(Person.builder().id("002").age(40).build());

What is the best way to get in Java 8 a subset of persons, where person.id().equals(age.id()) for each item person in persons and age in ages?

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Abhi Nandan
  • 195
  • 3
  • 11

2 Answers2

6

You can create a Set of ids of the people in ages collection.

Set<String> ageIds = ages.stream().map(Person::getId).collect(Collectors.toSet());

and further, use it to filter each person item in the resulting subset based on the query if the above set contains its id.

List<Person> subset = persons.stream()
        .filter(p -> ageIds.contains(p.getId()))
        .collect(Collectors.toList());
Naman
  • 27,789
  • 26
  • 218
  • 353
0

You can have that using two streams, too:

public static void main(String[] args) {
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person("001", "alpha", 22));
    persons.add(new Person("002", "beta", 49));
    persons.add(new Person("003", "gamma", 37));

    List<Person> ages = new ArrayList<Person>();
    ages.add(new Person("001", "alpha", 22));
    ages.add(new Person("002", "beta", 49));

    // stream the persons
    Set<Person> subset = persons.stream()
            // and filter by anything of the stream of ages
            .filter(p -> ages.stream()
                    // that matches the id of the current Person
                    .anyMatch(a -> a.getId().equals(p.getId()))
            )
            // collect them in a Set
            .collect(Collectors.toSet());

    subset.forEach(System.out::println);
}

Output on my system:

[001, alpha, 22]
[002, beta, 49]

with a proper toString() method, of course…

deHaar
  • 17,687
  • 10
  • 38
  • 51