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?

2
  • 1
    streams using filter Commented Nov 19, 2019 at 13:41
  • SELECT * FROM persons JOIN ages ON persons.id = ages.id Commented Nov 19, 2019 at 13:49

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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…

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.