-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
PriorityQueueToStreamTest.java
84 lines (66 loc) · 2.68 KB
/
PriorityQueueToStreamTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.pivovarit.priority;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
class PriorityQueueToStreamTest {
static <T> Stream<T> drainToStream(PriorityQueue<T> queue) {
Objects.requireNonNull(queue);
return Stream.generate(queue::poll)
.limit(queue.size());
}
static <T> Stream<T> drainToStreamJava9(PriorityQueue<T> queue) {
Objects.requireNonNull(queue);
return Stream.generate(queue::poll)
.takeWhile(Objects::nonNull);
}
static <T> Stream<T> asStream(PriorityQueue<T> queue) {
Objects.requireNonNull(queue);
Comparator<? super T> comparator = queue.comparator();
return comparator != null
? queue.stream().sorted(comparator)
: queue.stream().sorted();
}
@Test
void shouldMaintainInsertionOrder() {
PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparing(String::length));
List<String> content = Arrays.asList("1", "333", "22", "55555", "4444");
queue.addAll(content);
assertThat(queue.stream())
.containsExactlyElementsOf(content);
}
@Test
void solution_1() throws Exception {
PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparing(String::length));
queue.addAll(Arrays.asList("1", "333", "22", "55555", "4444"));
List<String> result = Stream.generate(queue::poll)
.limit(queue.size())
.collect(Collectors.toList());
assertThat(result).containsExactly("1", "22", "333", "4444", "55555");
assertThat(queue).isEmpty();
}
@Test
void solution_2() throws Exception {
PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparing(String::length));
queue.addAll(Arrays.asList("1", "333", "22", "55555", "4444"));
List<String> result = queue.stream()
.sorted(queue.comparator())
.collect(Collectors.toList());
assertThat(result).containsExactly("1", "22", "333", "4444", "55555");
assertThat(queue).isNotEmpty();
}
@Test
void solution_2_comparable() throws Exception {
PriorityQueue<String> queue = new PriorityQueue<>(Arrays.asList("1", "333", "22", "55555", "4444"));
List<String> result = queue.stream()
.sorted()
.collect(Collectors.toList());
assertThat(result).containsExactly("1", "22", "333", "4444", "55555");
assertThat(queue).isNotEmpty();
}
}