Skip to content

Commit 5cfb7b0

Browse files
tomekl007pedja4
authored andcommitted
BAEL-906 code for min max priority queue and evicting queue (eugenp#1827)
* BAEL-906 code for min max priority queue and evicting queue * BAEL-906 simplify example * BAEL-906 test method renamed
1 parent c5766f2 commit 5cfb7b0

2 files changed

Lines changed: 97 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package org.baeldung.guava;
2+
3+
4+
import com.google.common.collect.EvictingQueue;
5+
import org.junit.Test;
6+
7+
import java.util.Queue;
8+
import java.util.stream.IntStream;
9+
10+
import static org.assertj.core.api.Java6Assertions.assertThat;
11+
12+
public class EvictingQueueTest {
13+
14+
@Test
15+
public void givenEvictingQueue_whenAddElementToFull_thenShouldEvictOldestItem() {
16+
//given
17+
Queue<Integer> evictingQueue = EvictingQueue.create(10);
18+
19+
//when
20+
IntStream.range(0, 10).forEach(evictingQueue::add);
21+
22+
//then
23+
assertThat(evictingQueue).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
24+
25+
//and
26+
evictingQueue.add(100);
27+
28+
//then
29+
assertThat(evictingQueue).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 100);
30+
}
31+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package org.baeldung.guava;
2+
3+
4+
import com.google.common.collect.MinMaxPriorityQueue;
5+
import org.junit.Test;
6+
7+
import java.util.Comparator;
8+
import java.util.stream.IntStream;
9+
10+
import static org.assertj.core.api.Assertions.assertThat;
11+
12+
public class MinMaxPriorityQueueTest {
13+
@Test
14+
public void givenMinMaxPriorityQueue_whenAddElementToFull_thenShouldEvictGreatestItem() {
15+
//given
16+
MinMaxPriorityQueue<CustomClass> queue = MinMaxPriorityQueue
17+
.orderedBy(Comparator.comparing(CustomClass::getValue))
18+
.maximumSize(10)
19+
.create();
20+
21+
//when
22+
IntStream
23+
.iterate(10, i -> i - 1)
24+
.limit(10)
25+
.forEach(i -> queue.add(new CustomClass(i)));
26+
27+
//then
28+
assertThat(queue.peekFirst().getValue()).isEqualTo(1);
29+
assertThat(queue.peekLast().getValue()).isEqualTo(10);
30+
31+
32+
//and
33+
queue.add(new CustomClass(-1));
34+
35+
36+
//then
37+
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
38+
assertThat(queue.peekLast().getValue()).isEqualTo(9);
39+
40+
//and
41+
queue.add(new CustomClass(100));
42+
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
43+
assertThat(queue.peekLast().getValue()).isEqualTo(9);
44+
45+
}
46+
47+
48+
class CustomClass {
49+
private final Integer value;
50+
51+
CustomClass(Integer value) {
52+
this.value = value;
53+
}
54+
55+
public Integer getValue() {
56+
return value;
57+
}
58+
59+
@Override
60+
public String toString() {
61+
return "CustomClass{" +
62+
"value=" + value +
63+
'}';
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)