diff --git a/guava/src/test/java/org/baeldung/guava/EvictingQueueTest.java b/guava/src/test/java/org/baeldung/guava/EvictingQueueTest.java new file mode 100644 index 0000000000..7758dcd975 --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/EvictingQueueTest.java @@ -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 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); + } +} diff --git a/guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueTest.java b/guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueTest.java new file mode 100644 index 0000000000..f75b5a9bcb --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueTest.java @@ -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 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 + + '}'; + } + } +}