Brennan Bennett
Brennan Bennett

Reputation: 95

How do I return objects with lambdas java

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?

Upvotes: 1

Views: 76

Answers (2)

eric.v
eric.v

Reputation: 615

I'll do this:

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

Cheers

Upvotes: 0

Nicolas Filotto
Nicolas Filotto

Reputation: 44995

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);
}

Upvotes: 1

Related Questions