Filtering Values While Iterating
A filter retains the original items satisfying a predicate, typically in the order they were visited.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
State the condition
Given scores 3, 8, 5, and 8, retaining scores at least six yields 8 and 8. A filter preserves both copies unless uniqueness is another requirement. A named predicate function can document the eligibility rule.
Check stability of the output
Filtering by oddness in 5, 2, and 3 yields 5 then 3 when traversed in order. An intermediate set may remove duplicates and change the order. Read your example input and output for evidence about multiplicity and order before choosing a container.[1]
Preserve exactly the items satisfying the predicate
A scan of names ["B", "A", "B", "C"] keeping entries different from A should give B, B, C under an order-preserving filter. Replacing the output with a set loses the second B and may change order. Sorting the retained values can also differ from filtering alone. Read the output contract and make a sample with repeated values and distinctive positions. Ordered and unordered collection equality explains why different assertions answer different questions.
Name and test the selection rule independently
For a predicate selecting temperatures at least 20, try 19, 20, and 21. The output should retain both 20 and 21 with the original values, without changing them during selection. A follow-up transformation can map those values to another scale. Transforming an item in a loop describes that second operation.
If filtering stands before a later validation step, be explicit about whether it can conceal invalid data. A field missing its temperature could be treated as ineligible, or it could be a required error. Include that case and verify the reported result. If the goal needs original row positions, enumerate before selecting.