google / mug

A small Java 8 library (string manipulation, stream utils)
Apache License 2.0
367 stars 65 forks source link

BiStream.sortedBy[Values,Keys] gives unexpected output #8

Closed andrewparmet closed 6 years ago

andrewparmet commented 6 years ago

Hello,

Sorting a BiStream seems to be giving odd output that looks like a bug. Here is a test case that exhibits the issue:

  @Test
  public void test() {
    BiStream.from(
        ImmutableMap.of(
            "key-a", 1,
            "key-b", 1))
    .mapValues((k, v) -> v * 10)
    .sortedByValues(Integer::compare)
    .forEach((k, v) -> System.out.println(k + " " + v));
  }

I would expect output:

key-a 10
key-b 10

but the printed output is:

key-b 10
key-b 10

Both the sort and the map call are necessary for this to manifest. The same behavior occurs if I use sortedByKeys(String::compareTo). Do you have any suggestions about where things are going wrong?

Thanks!

andrewparmet commented 6 years ago

I've done some digging and I'm seeing some behavior that looks suspicious: the same EphemeralEntry current is being placed in a SortedOps temporary list twice that is sorted at the end of stream execution. That object was the container for the mapped values, but since it is reused, at the moment of consumption its value is the mapped value of the last item in the stream.

On their own, neither operation triggers the creation of EphemeralEntries - it looks like they delegate directly to their underlying streams so this is avoided.

It looks like this changed from version 1.10 to 1.11: https://github.com/google/mug/compare/e787aed...6e3c0f0

andrewparmet commented 6 years ago

Closed with merge of #9.