Question: I have the following data frame my\_df:

```
Name      cards
------------------
John      {A,B}
Mary      {B,C,A}
Dan       {D,A}
Peter     {C,A}
Ed        {A,C,D}

```

and I want to do a binary encoding for the set values, i.e. I want the output to be like:

```
Name     Card_A    Card_B    Card_C   Card_D
--------------------------------------------
John      1          1         0        0
Mary      1          1         1        0
Dan       1          0         0        1
Peter     1          0         1        0
Ed        1          0         1        1

```

Is there an existing python package for this? Or what would be the best way to achieve this? Thanks!

Answer: 
It might be tempting to use

```
long count = stream.peek(action).count();

```

and it may appear to work. However, `peek`’s action will only be performed when an element is being processed, but for some streams, the count may be available without processing the elements. Java 9 is going to take this opportunity, which makes the code above fail to perform `action` for some streams.

You can use a `collect` operation that doesn’t allow to take short-cuts, e.g.

```
long count = stream.collect(
    Collectors.mapping(s -> { action.accept(s); return s; }, Collectors.counting()));

```

or

```
long count = stream.collect(Collectors.summingLong(s -> { action.accept(s); return 1; }));

```
This can be done with `peek` function, as it returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

```
AtomicInteger counter = new AtomicInteger(0);

elements 
  .stream()
  .forEach(doSomething())
  .peek(elem -> counter.incrementAndGet());

int elementsProcessed = counter.get();

```