Skip to content

Instantly share code, notes, and snippets.

@minborg
Created September 20, 2018 13:20
Show Gist options
  • Save minborg/34b7b04342d4b2866c9af12f187c0a51 to your computer and use it in GitHub Desktop.
Save minborg/34b7b04342d4b2866c9af12f187c0a51 to your computer and use it in GitHub Desktop.
package com.example;
import com.speedment.common.combinatorics.Permutation;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.*;
final class StreamTest {
UnaryOperator<Stream<String>> FILTER_OP = new UnaryOperator<Stream<String>>() {
@Override
public Stream<String> apply(Stream<String> s) {
return s.filter(string -> string.length() > 1);
}
@Override
public String toString() {
return "filter";
}
};
UnaryOperator<Stream<String>> DISTINCT_OP = new UnaryOperator<Stream<String>>() {
@Override
public Stream<String> apply(Stream<String> s) {
return s.distinct();
}
@Override
public String toString() {
return "distinct";
}
};
UnaryOperator<Stream<String>> SORTED_OP = new UnaryOperator<Stream<String>>() {
@Override
public Stream<String> apply(Stream<String> s) {
return s.sorted();
}
@Override
public String toString() {
return "sorted";
}
};
@Test
void test() {
List<String> actual = Stream.of("CCC", "A", "BB", "BB")
.filter(string -> string.length() > 1)
.sorted()
.distinct()
.collect(toList());
List<String> expected = Arrays.asList("BB", "CCC");
assertEquals(actual, expected);
}
@Test
void demoPermutations() {
Permutation.of("A", "B", "C")
.map(
is -> is.collect(toList())
)
.forEach(System.out::println);
}
@Test
void printAllPermutations() {
Permutation.of(
FILTER_OP,
DISTINCT_OP,
SORTED_OP
)
.map(
is -> is.collect(toList())
)
.forEach(System.out::println);
}
@TestFactory
Stream<DynamicTest> testDynamicTestStream() {
return Stream.of(
DynamicTest.dynamicTest("A", () -> assertEquals("A", "A")),
DynamicTest.dynamicTest("B", () -> assertEquals("B", "B"))
);
}
@TestFactory
Stream<DynamicTest> testAllPermutations() {
List<String> expected = Arrays.asList("BB", "CCC");
return Permutation.of(
FILTER_OP,
DISTINCT_OP,
SORTED_OP
)
.map(is -> is.collect(toList()))
.map(l -> DynamicTest.dynamicTest(
l.toString(),
() -> {
List<String> actual = l.stream()
.reduce(
Stream.of("CCC", "A", "BB", "BB"),
(s, oper) -> oper.apply(s),
(a, b) -> a
).collect(toList());
assertEquals(expected, actual);
}
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment