1

Say I have a List addressees, and the properties for the address are
1. ID
2. Name
3. State
Then I have a get method to get an address by ID

public Address get(Integer id) {
    for (Address myAddress : addresses) {
        if (myAddress.getId() == id) {
            return myAddress;
        }
    }
    return null;
}

This is how it would look without lambdas
How do I return the address using lambdas?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122

2 Answers2

1

It should according to your context something like:

// Find any address that matches
addresses.stream().filter(a -> a.getId() == id).findAny();

or

// Find the first address that matches
addresses.stream().filter(a -> a.getId() == id).findFirst();

The first approach is mostly interesting in case you want to parallelize the search using addresses.parallelStream().filter(a -> a.getId() == id).findAny(), it will be much faster than the second approach as it will stop seeking as soon as we have a result. The second approach is more interesting in case you don't intend to parallelize it which seems to be your case here.

So finally, it gives:

public Address get(Integer id) {
    return addresses.stream()
        .filter(a -> a.getId() == id)
        .findFirst().orElse(null);
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
0

I'll do this:

public Address get(Integer id) {
    return addresses.stream()
        .filter(a -> a.getId().equals(id))
        .findFirst()
        .orElse(null);
}

Cheers

eric.v
  • 605
  • 5
  • 9