BAEL-906 code for min max priority queue and evicting queue (#1827)

* BAEL-906 code for min max priority queue and evicting queue

* BAEL-906 simplify example

* BAEL-906 test method renamed
This commit is contained in:
Tomasz Lelek 2017-05-12 14:12:22 +02:00 committed by pedja4
parent c5766f2bfe
commit 5cfb7b0979
2 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package org.baeldung.guava;
import com.google.common.collect.EvictingQueue;
import org.junit.Test;
import java.util.Queue;
import java.util.stream.IntStream;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class EvictingQueueTest {
@Test
public void givenEvictingQueue_whenAddElementToFull_thenShouldEvictOldestItem() {
//given
Queue<Integer> evictingQueue = EvictingQueue.create(10);
//when
IntStream.range(0, 10).forEach(evictingQueue::add);
//then
assertThat(evictingQueue).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
//and
evictingQueue.add(100);
//then
assertThat(evictingQueue).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 100);
}
}

View File

@ -0,0 +1,66 @@
package org.baeldung.guava;
import com.google.common.collect.MinMaxPriorityQueue;
import org.junit.Test;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
public class MinMaxPriorityQueueTest {
@Test
public void givenMinMaxPriorityQueue_whenAddElementToFull_thenShouldEvictGreatestItem() {
//given
MinMaxPriorityQueue<CustomClass> queue = MinMaxPriorityQueue
.orderedBy(Comparator.comparing(CustomClass::getValue))
.maximumSize(10)
.create();
//when
IntStream
.iterate(10, i -> i - 1)
.limit(10)
.forEach(i -> queue.add(new CustomClass(i)));
//then
assertThat(queue.peekFirst().getValue()).isEqualTo(1);
assertThat(queue.peekLast().getValue()).isEqualTo(10);
//and
queue.add(new CustomClass(-1));
//then
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
assertThat(queue.peekLast().getValue()).isEqualTo(9);
//and
queue.add(new CustomClass(100));
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
assertThat(queue.peekLast().getValue()).isEqualTo(9);
}
class CustomClass {
private final Integer value;
CustomClass(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
@Override
public String toString() {
return "CustomClass{" +
"value=" + value +
'}';
}
}
}