|
| 1 | +package com.baeldung.collectors; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Objects; |
| 6 | + |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import static java.util.stream.Collectors.maxBy; |
| 10 | +import static java.util.stream.Collectors.minBy; |
| 11 | +import static java.util.stream.Collectors.teeing; |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | + |
| 14 | +/** |
| 15 | + * Unit tests for collectors additions in Java 12. |
| 16 | + */ |
| 17 | +public class CollectorsUnitTest { |
| 18 | + |
| 19 | + @Test |
| 20 | + public void whenTeeing_ItShouldCombineTheResultsAsExpected() { |
| 21 | + List<Integer> numbers = Arrays.asList(42, 4, 2, 24); |
| 22 | + Range range = numbers.stream() |
| 23 | + .collect(teeing( |
| 24 | + minBy(Integer::compareTo), |
| 25 | + maxBy(Integer::compareTo), |
| 26 | + (min, max) -> new Range(min.orElse(null), max.orElse(null)) |
| 27 | + )); |
| 28 | + |
| 29 | + assertThat(range).isEqualTo(new Range(2, 42)); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Represents a closed range of numbers between {@link #min} and |
| 34 | + * {@link #max}, both inclusive. |
| 35 | + */ |
| 36 | + private static class Range { |
| 37 | + |
| 38 | + private final Integer min; |
| 39 | + |
| 40 | + private final Integer max; |
| 41 | + |
| 42 | + Range(Integer min, Integer max) { |
| 43 | + this.min = min; |
| 44 | + this.max = max; |
| 45 | + } |
| 46 | + |
| 47 | + Integer getMin() { |
| 48 | + return min; |
| 49 | + } |
| 50 | + |
| 51 | + Integer getMax() { |
| 52 | + return max; |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public boolean equals(Object o) { |
| 57 | + if (this == o) return true; |
| 58 | + if (o == null || getClass() != o.getClass()) return false; |
| 59 | + Range range = (Range) o; |
| 60 | + return Objects.equals(getMin(), range.getMin()) && |
| 61 | + Objects.equals(getMax(), range.getMax()); |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public int hashCode() { |
| 66 | + return Objects.hash(getMin(), getMax()); |
| 67 | + } |
| 68 | + |
| 69 | + @Override |
| 70 | + public String toString() { |
| 71 | + return "Range{" + |
| 72 | + "min=" + min + |
| 73 | + ", max=" + max + |
| 74 | + '}'; |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments