A.BC
A.BC

Reputation: 79

How can I filter directly a collection based on a value?

I would like to know how can I get all the elements from a collection containing a specific value.

Like this:

@Override
public Collection<Sale> selectSales(String map) {
    HashSet<Sale> sales = new HashSet();

    for (Sale sale : salesList) {
        if (sale.getMap().equals(map)) {
            sales.add(sale);
        }
    }
    return sales;
}

But I would like to filter the collection directly. I read that I can do this using LAMBDA, example:

list.removeIf(c -> c.getCarColor() == Color.BLUE);

But I Don't know how to apply this example.

Thank you.

Upvotes: 5

Views: 326

Answers (2)

Andrew
Andrew

Reputation: 49606

Judging by the method name selectSales, you don't want to remove entries from the original list, you want to construct a new collection copying elements from the source and filtering out some values by a condition.

The condition is sale.getMap().equals(mapName). Note that I used mapName instead of map which seems to be a typo.

salesList.stream()
         .filter(sale -> sale.getMap().equals(mapName))
         .collect(Collectors.toList());

Assuming that salesList isn't null, a more robust version of the method would look like

public Collection<Sale> selectSales(String mapName) {
    Objects.requireNonNull(mapName, "mapName");

    return salesList.stream()
             .filter(sale -> mapName.equals(sale.getMap()))
             .collect(Collectors.toList());
}

Upvotes: 4

Ousmane D.
Ousmane D.

Reputation: 56423

use a stream and filter:

salesList.stream()
         .filter(sale -> sale.getMap().equals(mapName)) // I've changed map to mapName as I am assuming that was a mistake
         .collect(Collectors.toCollection(HashSet::new));

This retains elements which satisfy the provided predicate sale -> sale.getMap().equals(mapName).

Note the above does not modify the source, if you want to modify the source then proceed with removeIf:

salesList.removeIf(sale -> !sale.getMap().equals(mapName));

This removes the elements which satisfy the provided predicate sale -> !sale.getMap().equals(mapName).

Upvotes: 7

Related Questions