Each: Canonical Element-Wise Traversal

Get a container's natural traversal from one each() call, and give your own containers one too.

"Simplicity is the ultimate sophistication."

– Leonardo da Vinci

What You'll Learn

  • Get a traversal for a JDK container from EachInstances, or for Maybe, Either, Try and Validated from EachExtensions
  • Number list elements, or adjust map values by key, through EachIndexed.indexedTraversal()
  • Traverse a container a Focus path does not recognise with .each(Each)
  • Write an Each instance for your own container, or wrap an existing traversal with Each.fromTraversal
  • Decide between Each and a hand-built Traversal

See Example Code

Every container type has a natural way to traverse its elements. A List iterates from first to last. A Map visits each value. An Optional yields zero or one element. The Each type class captures this canonical traversal pattern, providing a uniform interface across diverse container types.

Rather than writing traversal logic repeatedly for each container, Each gives you a single method: each(). Call it, receive a Traversal, and you're ready to read or modify all elements. Each plays the part of Iterable: Java's enhanced for loop works on anything that supplies an iterator, and each() works on any container with an Each instance. Unlike Iterable, whose iterator only reads, the traversal each() returns also writes, giving back a new container.


The Problem: Repeated Traversal Patterns

When working with different container types, you often need similar traversal operations:

// List: traverse all elements
Traversal<List<String>, String> listTraversal = Traversals.forList();

// Map: traverse all values
Traversal<Map<String, Integer>, Integer> mapTraversal = Traversals.forMapValues();

// Optional: traverse the value if present
Traversal<Optional<String>, String> optTraversal = Traversals.forOptional();

// Each time you need a traversal, you must know which factory method to use

With Each, the pattern becomes uniform:

// Get the canonical traversal for any container
Traversal<List<String>, String> listTrav = EachInstances.<String>listEach().each();
Traversal<Map<String, Integer>, Integer> mapTrav = EachInstances.<String, Integer>mapValuesEach().each();
Traversal<Optional<String>, String> optTrav = EachInstances.<String>optionalEach().each();

More importantly, Each integrates with the Focus DSL, enabling fluent navigation through any container type.


The Each Type Class

@FunctionalInterface
public interface Each<S, A> {

    // The canonical traversal for all elements
    Traversal<S, A> each();

    // Check if indexed access is supported (i.e. this is an EachIndexed)
    default boolean supportsIndexed() {
        return this instanceof EachIndexed<?, ?, ?>;
    }
}

// Containers with a meaningful index implement EachIndexed, which fixes the
// index type I at the type level.
public interface EachIndexed<I, S, A> extends Each<S, A> {
    IndexedTraversal<I, S, A> indexedTraversal();
}

The interface is simple by design. Implement each() to provide a traversal; if your container has meaningful indices, implement EachIndexed and provide indexedTraversal() instead.


Available Each Instances

Standard Java Types (EachInstances)

Typeeach()Indexed?Index typeFactory
List<A>✓✓IntegerlistEach()
Set<A>✓setEach()
Collection<A>✓collectionEach()
Map<K, V>✓✓KmapValuesEach()
Optional<A>✓optionalEach()
A[]✓✓IntegerarrayEach()
Stream<A>✓streamEach()
VStream<A>✓vstreamEach()
String✓✓IntegerstringCharsEach(), focusing Character
import org.higherkindedj.optics.each.EachInstances;

// List traversal with index support
EachIndexed<Integer, List<String>, String> listEach = EachInstances.listEach();

// Set traversal (no meaningful index)
Each<Set<Integer>, Integer> setEach = EachInstances.setEach();

// Collection traversal: a set comes back a set, anything else comes back a list
Each<Collection<String>, String> collectionEach = EachInstances.collectionEach();

// Map values traversal with key as index
EachIndexed<String, Map<String, Double>, Double> mapEach = EachInstances.mapValuesEach();

// Optional traversal (0 or 1 element)
Each<Optional<String>, String> optEach = EachInstances.optionalEach();

// Array traversal with index support
EachIndexed<Integer, Integer[], Integer> arrayEach = EachInstances.arrayEach();

// Stream traversal (consumed during traversal)
Each<Stream<String>, String> streamEach = EachInstances.streamEach();

// VStream traversal (materialises during traversal; finite streams only)
Each<VStream<String>, String> vstreamEach = EachInstances.vstreamEach();

// String character traversal with index support
EachIndexed<Integer, String, Character> stringEach = EachInstances.stringCharsEach();

HKT Types (EachExtensions)

For Higher-Kinded-J core types, use EachExtensions:

Typeeach()Indexed?FactoryFocuses
Maybe<A>✓maybeEach()the value when present
Either<L, R>✓eitherRightEach()the right side only
Try<A>✓trySuccessEach()the success only
Validated<E, A>✓validatedEach()the valid side only
import org.higherkindedj.optics.extensions.EachExtensions;

// Maybe traversal (0 or 1 element)
Each<Maybe<String>, String> maybeEach = EachExtensions.maybeEach();

// Either right value traversal
Each<Either<AppError, Payload>, Payload> eitherEach = EachExtensions.eitherRightEach();

// Try success value traversal
Each<Try<String>, String> tryEach = EachExtensions.trySuccessEach();

// Validated valid value traversal
Each<Validated<List<AppError>, Payload>, Payload> validatedEach = EachExtensions.validatedEach();

Basic Usage

Traversing All Elements

    Each<List<String>, String> listEach = EachInstances.listEach();
    Traversal<List<String>, String> traversal = listEach.each();

    List<String> names = List.of("alice", "bob", "charlie");

    // Get all elements
    List<String> all = Traversals.getAll(traversal, names);
    // Result: ["alice", "bob", "charlie"]

    // Modify all elements
    List<String> upper = Traversals.modify(traversal, String::toUpperCase, names);
    // Result: ["ALICE", "BOB", "CHARLIE"]

    // Set all elements to the same value (set is modify with a constant)
    List<String> same = Traversals.modify(traversal, _ -> "anonymous", names);
    // Result: ["anonymous", "anonymous", "anonymous"]

Using Indexed Traversal

When position matters, type the instance as EachIndexed and call indexedTraversal(). The index type (Integer for lists) is fixed at compile time:

    EachIndexed<Integer, List<String>, String> listEach = EachInstances.listEach();
    IndexedTraversal<Integer, List<String>, String> indexed = listEach.indexedTraversal();

    List<String> items = List.of("apple", "banana", "cherry");

    // Number each element
    List<String> numbered =
        IndexedTraversals.imodify(indexed, (index, value) -> (index + 1) + ". " + value, items);
    // Result: ["1. apple", "2. banana", "3. cherry"]

Map Key as Index

For maps, the index is the key, so the EachIndexed index type is K:

    EachIndexed<String, Map<String, Integer>, Integer> mapEach = EachInstances.mapValuesEach();
    IndexedTraversal<String, Map<String, Integer>, Integer> indexed = mapEach.indexedTraversal();

    Map<String, Integer> scores = Map.of("alice", 100, "bob", 85, "charlie", 92);

    // Award a five-point bonus to one particular entrant, by key
    Map<String, Integer> adjusted =
        IndexedTraversals.imodify(
            indexed, (key, value) -> key.equals("bob") ? value + 5 : value, scores);
    // Result: {"alice": 100, "bob": 90, "charlie": 92}

    // A traversal cannot change the value type: imodify takes A -> A and returns the
    // same map type. To build a differently-typed map, extract the pairs and collect:
    Map<String, String> labelled =
        IndexedTraversals.toIndexedList(indexed, scores).stream()
            .collect(toMap(Pair::first, pair -> pair.first() + ": " + pair.second()));

Integration with Focus DSL

The Focus DSL is covered properly in Focus DSL; this section shows only where Each plugs into it, so skim it now and return when you reach that chapter.

The Focus DSL provides an .each(Each) method on FocusPath, AffinePath, and TraversalPath. This enables fluent navigation through custom container types:

// A depot's bays, each holding its stock by SKU
record Depot(String name, List<Bay> bays) {}
record Bay(String label, Map<String, Integer> stock) {}

// Create lenses
Lens<Depot, List<Bay>> baysLens = Lens.of(Depot::bays, (d, s) -> new Depot(d.name(), s));
Lens<Bay, Map<String, Integer>> stockLens = Lens.of(Bay::stock, (s, m) -> new Bay(s.label(), m));

// Navigate using Each instances
FocusPath<Depot, List<Bay>> depotBays = FocusPath.of(baysLens);

// Use listEach to traverse the bays
TraversalPath<Depot, Bay> allBays = depotBays.each(EachInstances.listEach());

// Continue navigation
TraversalPath<Depot, Map<String, Integer>> allStock = allBays.via(stockLens);

// Use mapValuesEach to traverse each SKU's stock level
TraversalPath<Depot, Integer> allLevels = allStock.each(EachInstances.mapValuesEach());

// Now restock every SKU in every bay
Depot restocked = allLevels.modifyAll(level -> level + 10, depot);

This is how a path steps into any container: a Map's values here, a List with EachInstances.listEach(), and your own container with the instance you give it.


Creating Custom Each Instances

A custom instance implements each() by writing the traversal's modifyF directly; its F extends WitnessArity<TypeArity.Unary> bound is the same one Traversal.modifyF carries, naming the applicative effect the traversal runs in.

For custom container types, implement the Each interface:

// A simple tree structure
public sealed interface Tree<A> {
    record Leaf<A>(A value) implements Tree<A> {}
    record Branch<A>(Tree<A> left, Tree<A> right) implements Tree<A> {}
}

// Each instance for Tree
public static <A> Each<Tree<A>, A> treeEach() {
    return new Each<>() {
        @Override
        public Traversal<Tree<A>, A> each() {
            return new Traversal<>() {
                @Override
                public <F extends WitnessArity<TypeArity.Unary>> Kind<F, Tree<A>> modifyF(
                        Function<A, Kind<F, A>> f,
                        Tree<A> source,
                        Applicative<F> app) {
                    return switch (source) {
                        case Tree.Leaf<A> leaf ->
                            app.map(Tree.Leaf::new, f.apply(leaf.value()));
                        case Tree.Branch<A> branch ->
                            app.map2(
                                modifyF(f, branch.left(), app),
                                modifyF(f, branch.right(), app),
                                Tree.Branch::new
                            );
                    };
                }
            };
        }
    };
}

From Existing Traversal

If you already have a Traversal, wrap it:

<A> Each<MyContainer<A>, A> eachOf(Traversal<MyContainer<A>, A> existingTraversal) {
    return Each.fromTraversal(existingTraversal);
}

From IndexedTraversal

If you have an IndexedTraversal, Each.fromIndexedTraversal returns an EachIndexed, so you get both the element and indexed traversals with the index type preserved:

<A> EachIndexed<Integer, MyList<A>, A> eachOf(IndexedTraversal<Integer, MyList<A>, A> indexed) {
    EachIndexed<Integer, MyList<A>, A> each = Each.fromIndexedTraversal(indexed);

    // Both work
    Traversal<MyList<A>, A> trav = each.each();
    IndexedTraversal<Integer, MyList<A>, A> iTrav = each.indexedTraversal();
    return each;
}

Each vs Traverse

You might wonder how Each relates to the Traverse type class from HKT. Here's the distinction:

AspectEach<S, A>Traverse
Works onConcrete types (List<A>, Map<K, V>)Higher-kinded types (Kind<F, A>)
ReturnsTraversal<S, A>Sequence/traverse methods
Use caseOptics compositionApplicative traversal
Java-friendlyVery (no Kind wrappers)Requires HKT encoding

Use Each when working with optics and standard Java collections. Use Traverse when working with HKT-encoded types and applicative effects.


Common Patterns

Bulk Validation

Each<List<Order>, Order> orderEach = EachInstances.listEach();
Traversal<List<Order>, Order> allOrders = orderEach.each();

// Validate all orders, accumulating errors
Validated<List<String>, List<Order>> result = VALIDATED.narrow(allOrders.modifyF(
    order -> validateOrder(order),
    orders,
    Instances.validated(Semigroups.list())
));

Conditional Modification with Index

EachIndexed<Integer, List<Product>, Product> productEach = EachInstances.listEach();
IndexedTraversal<Integer, List<Product>, Product> indexed = productEach.indexedTraversal();

// Apply discount to even-indexed products
List<Product> discounted = IndexedTraversals.imodify(
    indexed,
    (index, product) -> index % 2 == 0
        ? product.withPrice(product.price().multiply(new BigDecimal("0.9")))
        : product,
    products
);

Nested Container Navigation

// Contributor -> List<TaskBoard> -> Map<String, Task>
Each<List<TaskBoard>, TaskBoard> boardEach = EachInstances.listEach();
Each<Map<String, Task>, Task> taskEach = EachInstances.mapValuesEach();

TraversalPath<Contributor, Task> allTasks =
    FocusPath.of(contributorBoardsLens)
        .each(boardEach)
        .via(boardTasksLens)
        .each(taskEach);

// Update all tasks across all boards
Contributor updated = allTasks.modifyAll(Task::escalated, contributor);

When to Use Each

Use Each when:

  • You need a canonical traversal for a container type
  • Integrating with Focus DSL's .each(Each) method
  • Building reusable optics for custom containers
  • You want indexed access, through EachIndexed, where the container has an index

Use direct Traversal when:

  • You need a non-canonical traversal (e.g., every second element)
  • The traversal is one-off and doesn't need reuse
  • Performance is critical and you want to avoid the extra indirection

Key Takeaways

  • Each<S, A> provides a canonical Traversal<S, A> for any container type
  • EachInstances covers Java collections: List, Set, Collection, Map, Optional, arrays, Stream, VStream, String
  • EachExtensions covers HKT types: Maybe, Either, Try, Validated
  • EachIndexed.indexedTraversal() returns an IndexedTraversal when the container supports meaningful indices
  • Focus DSL integration via .each(Each) enables fluent navigation through custom containers
  • Each.fromTraversal() and Each.fromIndexedTraversal() wrap existing optics

See Also


Previous: Indexed Optics: Advanced Patterns Next: String Traversals