From 98633dce67678aa12db0a3f03474a231214856db Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 8 Jul 2017 06:51:41 +0200 Subject: [PATCH 1/8] Beal 1006 rate limmiter (#2224) * BAEL-1006 rate limiter tests * BAEL-1006 simpler example --- .../baeldung/guava/RateLimiterUnitTest.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java b/guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java new file mode 100644 index 0000000000..eb848e56fd --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java @@ -0,0 +1,81 @@ +package org.baeldung.guava; + + +import com.google.common.util.concurrent.RateLimiter; +import org.junit.Test; + +import java.time.ZonedDateTime; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RateLimiterUnitTest { + + @Test + public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() { + //given + RateLimiter rateLimiter = RateLimiter.create(100); + + //when + long startTime = ZonedDateTime.now().getSecond(); + IntStream.range(0, 1000).forEach(i -> { + rateLimiter.acquire(); + doSomeLimitedOperation(); + }); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds >= 10); + } + + @Test + public void givenLimitedResource_whenRequestTwice_thenShouldPermitWithoutBlocking() { + //given + RateLimiter rateLimiter = RateLimiter.create(2); + + //when + long startTime = ZonedDateTime.now().getSecond(); + rateLimiter.acquire(1); + doSomeLimitedOperation(); + rateLimiter.acquire(1); + doSomeLimitedOperation(); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds <= 1); + } + + @Test + public void givenLimitedResource_whenRequestOnce_thenShouldPermitWithoutBlocking() { + //given + RateLimiter rateLimiter = RateLimiter.create(100); + + //when + long startTime = ZonedDateTime.now().getSecond(); + rateLimiter.acquire(100); + doSomeLimitedOperation(); + long elapsedTimeSeconds = ZonedDateTime.now().getSecond() - startTime; + + //then + assertThat(elapsedTimeSeconds <= 1); + } + + @Test + public void givenLimitedResource_whenTryAcquire_shouldNotBlockIndefinitely() { + //given + RateLimiter rateLimiter = RateLimiter.create(1); + + //when + boolean result = rateLimiter.tryAcquire(2, 1, TimeUnit.SECONDS); + + //then + assertThat(result).isFalse(); + + } + + private void doSomeLimitedOperation() { + //some computing + } + +} From fdd26c7c528962584230cbb37dedbae33cb36c24 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 8 Jul 2017 07:58:42 +0200 Subject: [PATCH 2/8] Refactor awaitility (#2226) * Awaitility refactor * Refactor --- .../com/baeldung/awaitility/AsyncService.java | 24 ++++++----- .../awaitility/AsyncServiceUnitTest.java | 43 ++++++++++--------- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java b/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java index 3bc82afaac..adfa3e1fb2 100644 --- a/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java +++ b/libraries/src/main/java/com/baeldung/awaitility/AsyncService.java @@ -8,25 +8,23 @@ public class AsyncService { private final int DELAY = 1000; private final int INIT_DELAY = 2000; - private AtomicLong value = new AtomicLong(0); - private Executor executor = Executors.newFixedThreadPool(4); + private final AtomicLong value = new AtomicLong(0); + private final Executor executor = Executors.newFixedThreadPool(4); private volatile boolean initialized = false; - public void initialize() { + void initialize() { executor.execute(() -> { sleep(INIT_DELAY); initialized = true; }); } - public boolean isInitialized() { + boolean isInitialized() { return initialized; } - public void addValue(long val) { - if (!isInitialized()) { - throw new IllegalStateException("Service is not initialized"); - } + void addValue(long val) { + throwIfNotInitialized(); executor.execute(() -> { sleep(DELAY); value.addAndGet(val); @@ -34,9 +32,7 @@ public class AsyncService { } public long getValue() { - if (!isInitialized()) { - throw new IllegalStateException("Service is not initialized"); - } + throwIfNotInitialized(); return value.longValue(); } @@ -47,4 +43,10 @@ public class AsyncService { e.printStackTrace(); } } + + private void throwIfNotInitialized() { + if (!initialized) { + throw new IllegalStateException("Service is not initialized"); + } + } } diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java index 4f07d556b9..677d989fba 100644 --- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java +++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceUnitTest.java @@ -1,19 +1,20 @@ package com.baeldung.awaitility; +import org.awaitility.Awaitility; +import org.awaitility.Duration; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + import static org.awaitility.Awaitility.await; import static org.awaitility.Awaitility.fieldIn; import static org.awaitility.Awaitility.given; import static org.awaitility.proxy.AwaitilityClassProxy.to; import static org.hamcrest.Matchers.equalTo; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import org.awaitility.Awaitility; -import org.awaitility.Duration; -import org.junit.Before; -import org.junit.Test; - public class AsyncServiceUnitTest { private AsyncService asyncService; @@ -25,18 +26,18 @@ public class AsyncServiceUnitTest { @Test public void givenAsyncService_whenInitialize_thenInitOccurs1() { asyncService.initialize(); - Callable isInitialized = () -> asyncService.isInitialized(); + Callable isInitialized = asyncService::isInitialized; await().until(isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs2() { asyncService.initialize(); - Callable isInitialized = () -> asyncService.isInitialized(); + Callable isInitialized = asyncService::isInitialized; await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS) - .atMost(Duration.FIVE_SECONDS) - .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) - .until(isInitialized); + .atMost(Duration.FIVE_SECONDS) + .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS) + .until(isInitialized); } @Test @@ -46,7 +47,7 @@ public class AsyncServiceUnitTest { Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); asyncService.initialize(); - await().until(() -> asyncService.isInitialized()); + await().until(asyncService::isInitialized); } @Test @@ -59,14 +60,14 @@ public class AsyncServiceUnitTest { public void givenAsyncService_whenInitialize_thenInitOccurs3() { asyncService.initialize(); await().until(fieldIn(asyncService) - .ofType(boolean.class) - .andWithName("initialized"), equalTo(true)); + .ofType(boolean.class) + .andWithName("initialized"), equalTo(true)); } @Test public void givenValue_whenAddValue_thenValueAdded() { asyncService.initialize(); - await().until(() -> asyncService.isInitialized()); + await().until(asyncService::isInitialized); long value = 5; asyncService.addValue(value); await().until(asyncService::getValue, equalTo(value)); @@ -76,9 +77,9 @@ public class AsyncServiceUnitTest { public void givenAsyncService_whenGetValue_thenExceptionIgnored() { asyncService.initialize(); given().ignoreException(IllegalStateException.class) - .await() - .atMost(Duration.FIVE_SECONDS) - .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) - .until(asyncService::getValue, equalTo(0L)); + .await() + .atMost(Duration.FIVE_SECONDS) + .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS) + .until(asyncService::getValue, equalTo(0L)); } } From 647455b02998aea4549c00dd9ab03fb30eb5dad8 Mon Sep 17 00:00:00 2001 From: Ahmed Tawila Date: Sat, 8 Jul 2017 08:59:59 +0300 Subject: [PATCH 3/8] BAEL-994 - TemporalAdjuster in Java (#2227) * Evaluation article: Different Types of Bean Injection in Spring * added tests & changed configuration to Java-based config * removed xml config files * rename unit tests * BAEL-972 - Apache Commons Text * remove code from evaluation article * remove code from evaluation article * BAEL-972 - Apache Commons Text - added another example * BAEL-972 - Apache Commons Text - just indentation * BAEL-994 - TemporalAdjuster in Java --- .../CustomTemporalAdjuster.java | 23 +++++++ .../TemporalAdjusterUtil.java | 31 +++++++++ .../CustomTemporalAdjusterTest.java | 63 +++++++++++++++++++ .../TemporalAdjustersTest.java | 29 +++++++++ .../com/baeldung/text/StrBuilderTest.java | 6 +- 5 files changed, 149 insertions(+), 3 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java create mode 100644 core-java/src/main/java/com/baeldung/temporaladjuster/TemporalAdjusterUtil.java create mode 100644 core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java create mode 100644 core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java new file mode 100644 index 0000000000..ab491bee66 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -0,0 +1,23 @@ +package com.baeldung.temporaladjuster; + +import java.time.DayOfWeek; +import java.time.temporal.ChronoField; +import java.time.temporal.ChronoUnit; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAdjuster; + +public class CustomTemporalAdjuster implements TemporalAdjuster { + + @Override + public Temporal adjustInto(Temporal temporal) { + DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); + int daysToAdd; + if (dayOfWeek == DayOfWeek.FRIDAY) + daysToAdd = 3; + else if (dayOfWeek == DayOfWeek.SATURDAY) + daysToAdd = 2; + else + daysToAdd = 1; + return temporal.plus(daysToAdd, ChronoUnit.DAYS); + } +} diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/TemporalAdjusterUtil.java b/core-java/src/main/java/com/baeldung/temporaladjuster/TemporalAdjusterUtil.java new file mode 100644 index 0000000000..1a1528456e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/TemporalAdjusterUtil.java @@ -0,0 +1,31 @@ +package com.baeldung.temporaladjuster; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class TemporalAdjusterUtil { + + public static Calendar nextDayOfWeek(int dayOfWeek) { + Calendar date = Calendar.getInstance(); + int difference = dayOfWeek - date.get(Calendar.DAY_OF_WEEK); + if (!(difference > 0)) { + difference += 7; + } + date.add(Calendar.DAY_OF_MONTH, difference); + return date; + } + + @SuppressWarnings("static-access") + public static String getNextWorkingDay() { + Calendar calendar = Calendar.getInstance(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setCalendar(calendar); + if (calendar.DAY_OF_WEEK == Calendar.FRIDAY) + calendar.add(Calendar.DATE, 3); + if (calendar.DAY_OF_WEEK == Calendar.SATURDAY) + calendar.add(Calendar.DATE, 2); + else + calendar.add(Calendar.DATE, 1); + return format.format(calendar.getTime()); + } +} diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java new file mode 100644 index 0000000000..10dce5c498 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -0,0 +1,63 @@ +package com.baeldung.temporaladjusters; + +import java.text.SimpleDateFormat; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjuster; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.temporaladjuster.CustomTemporalAdjuster; +import com.baeldung.temporaladjuster.TemporalAdjusterUtil; + +public class CustomTemporalAdjusterTest { + + @Test + public void whenAdjustAndImplementInterface_thenNextWorkingDay() { + LocalDate localDate = LocalDate.now(); + CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); + LocalDate nextWorkingDay = localDate.with(temporalAdjuster); + + Assert.assertEquals(TemporalAdjusterUtil.getNextWorkingDay(), nextWorkingDay.toString()); + } + + @Test + public void whenAdjust_thenNextWorkingDay() { + LocalDate localDate = LocalDate.now(); + TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY; + LocalDate date = localDate.with(temporalAdjuster); + + Assert.assertEquals(TemporalAdjusterUtil.getNextWorkingDay(), date.toString()); + } + + @Test + public void whenAdjust_thenFourteenDaysFromToday() { + LocalDate localDate = LocalDate.now(); + TemporalAdjuster temporalAdjuster = (t) -> t.plus(Period.ofDays(14)); + LocalDate result = localDate.with(temporalAdjuster); + + Calendar calendar = Calendar.getInstance(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setCalendar(calendar); + calendar.add(Calendar.DATE, 14); + String fourteenDaysFromToday = format.format(calendar.getTime()); + + Assert.assertEquals(fourteenDaysFromToday, result.toString()); + } + + static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(today -> { + DayOfWeek dayOfWeek = today.getDayOfWeek(); + int daysToAdd; + if (dayOfWeek == DayOfWeek.FRIDAY) + daysToAdd = 3; + else if (dayOfWeek == DayOfWeek.SATURDAY) + daysToAdd = 2; + else + daysToAdd = 1; + return today.plusDays(daysToAdd); + }); +} diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java new file mode 100644 index 0000000000..f21da5cf75 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java @@ -0,0 +1,29 @@ +package com.baeldung.temporaladjusters; + +import java.text.SimpleDateFormat; +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.temporaladjuster.TemporalAdjusterUtil; + +public class TemporalAdjustersTest { + + @Test + public void whenAdjust_thenNextSunday() { + LocalDate localDate = LocalDate.now(); + LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); + + Calendar calendar = TemporalAdjusterUtil.nextDayOfWeek(Calendar.SUNDAY); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setCalendar(calendar); + String formattedDate = format.format(calendar.getTime()); + + Assert.assertEquals(formattedDate, nextSunday.toString()); + } + +} diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java index a8dbaadc5a..f08b43f69b 100644 --- a/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java +++ b/libraries/src/test/java/com/baeldung/text/StrBuilderTest.java @@ -5,12 +5,12 @@ import org.junit.Assert; import org.junit.Test; public class StrBuilderTest { - + @Test public void whenReplaced_thenCorrect() { StrBuilder strBuilder = new StrBuilder("example StrBuilder!"); strBuilder.replaceAll("example", "new"); - + Assert.assertEquals(new StrBuilder("new StrBuilder!"), strBuilder); } @@ -21,4 +21,4 @@ public class StrBuilderTest { Assert.assertEquals(new StrBuilder(""), strBuilder); } -} +} \ No newline at end of file From 94ee35bed7ec1dbb74bcc6a8336da7f0053c8163 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 8 Jul 2017 07:36:06 +0100 Subject: [PATCH 4/8] BAEL-965 - reverting to anonymous classes --- .../collections/CollectionUtilsGuideTest.java | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java index 9166865484..90e30b01dc 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java @@ -54,8 +54,10 @@ public class CollectionUtilsGuideTest { @Test public void givenListOfCustomers_whenTransformed_thenListOfAddress() { - Collection
addressCol = CollectionUtils.collect(list1, customer -> { - return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); + Collection
addressCol = CollectionUtils.collect(list1, new Transformer() { + public Address transform(Customer customer) { + return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); + } }); List
addressList = new ArrayList<>(addressCol); @@ -65,9 +67,13 @@ public class CollectionUtilsGuideTest { @Test public void givenCustomerList_whenFiltered_thenCorrectSize() { - - boolean isModified = CollectionUtils.filter(linkedList1, customer -> Arrays.asList("Daniel","Kyle").contains(customer.getName())); - + + boolean isModified = CollectionUtils.filter(linkedList1, new Predicate() { + public boolean evaluate(Customer customer) { + return Arrays.asList("Daniel","Kyle").contains(customer.getName()); + } + }); + //filterInverse does the opposite. It removes the element from the list if the Predicate returns true //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection From c598b937f07f7b5f1f19a55c6eec8ed7e524bd91 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 8 Jul 2017 08:43:14 +0200 Subject: [PATCH 5/8] RateLimiter fix (#2229) --- guava/src/main/java/org/baeldung/guava/CustomEvent.java | 4 ++-- guava/src/main/java/org/baeldung/guava/EventListener.java | 4 ++-- ...miterUnitTest.java => RateLimiterLongRunningUnitTest.java} | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) rename guava/src/test/java/org/baeldung/guava/{RateLimiterUnitTest.java => RateLimiterLongRunningUnitTest.java} (97%) diff --git a/guava/src/main/java/org/baeldung/guava/CustomEvent.java b/guava/src/main/java/org/baeldung/guava/CustomEvent.java index 2d5c3382d4..8534d7da1c 100644 --- a/guava/src/main/java/org/baeldung/guava/CustomEvent.java +++ b/guava/src/main/java/org/baeldung/guava/CustomEvent.java @@ -3,11 +3,11 @@ package org.baeldung.guava; public class CustomEvent { private String action; - public CustomEvent(String action) { + CustomEvent(String action) { this.action = action; } - public String getAction() { + String getAction() { return action; } diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java index 438fcade63..60beebeea5 100644 --- a/guava/src/main/java/org/baeldung/guava/EventListener.java +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -28,11 +28,11 @@ public class EventListener { eventsHandled++; } - public int getEventsHandled() { + int getEventsHandled() { return eventsHandled; } - public void resetEventsHandled() { + void resetEventsHandled() { eventsHandled = 0; } } diff --git a/guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java similarity index 97% rename from guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java rename to guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java index eb848e56fd..22041e78e5 100644 --- a/guava/src/test/java/org/baeldung/guava/RateLimiterUnitTest.java +++ b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java @@ -10,7 +10,7 @@ import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; -public class RateLimiterUnitTest { +public class RateLimiterLongRunningUnitTest { @Test public void givenLimitedResource_whenUseRateLimiter_thenShouldLimitPermits() { From d191622109498b2da9bd00970bedb36b842eb51a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sat, 8 Jul 2017 13:16:40 +0200 Subject: [PATCH 6/8] Ratelimiter fix (#2231) * RateLimiter fix * RateLimiter fix --- .../org/baeldung/guava/RateLimiterLongRunningUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java index 22041e78e5..914de01a6d 100644 --- a/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java +++ b/guava/src/test/java/org/baeldung/guava/RateLimiterLongRunningUnitTest.java @@ -67,7 +67,8 @@ public class RateLimiterLongRunningUnitTest { RateLimiter rateLimiter = RateLimiter.create(1); //when - boolean result = rateLimiter.tryAcquire(2, 1, TimeUnit.SECONDS); + rateLimiter.acquire(); + boolean result = rateLimiter.tryAcquire(2, 10, TimeUnit.MILLISECONDS); //then assertThat(result).isFalse(); From 57279a1b5cf07c2ad94e91b4ba9672093739385d Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 8 Jul 2017 19:30:39 +0200 Subject: [PATCH 7/8] BAEL-1005 bloom filter code (#2171) --- .../org/baeldung/guava/BloomFilterTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 guava/src/test/java/org/baeldung/guava/BloomFilterTest.java diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java new file mode 100644 index 0000000000..d7c25b7c8d --- /dev/null +++ b/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java @@ -0,0 +1,54 @@ +package org.baeldung.guava; + + +import com.google.common.hash.BloomFilter; +import com.google.common.hash.Funnels; +import org.junit.Test; + +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BloomFilterTest { + + @Test + public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 500, + 0.01); + + //when + filter.put(1); + filter.put(2); + filter.put(3); + + //then + // the probability that it returns true, but is actually false is 1% + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + + assertThat(filter.mightContain(100)).isFalse(); + } + + @Test + public void givenBloomFilter_whenAddNStringsToItMoreThanDefinedExpectedInsertions_thenItWillReturnTrueForAlmostAllElements() { + //when + BloomFilter filter = BloomFilter.create( + Funnels.integerFunnel(), + 5, + 0.01); + + //when + IntStream.range(0, 100_000).forEach(filter::put); + + + //then + assertThat(filter.mightContain(1)).isTrue(); + assertThat(filter.mightContain(2)).isTrue(); + assertThat(filter.mightContain(3)).isTrue(); + assertThat(filter.mightContain(1_000_000)).isTrue(); + } +} From 19577503828fcaa324731dcee198414455e21daa Mon Sep 17 00:00:00 2001 From: Devendra Tiwari Date: Sun, 9 Jul 2017 01:50:49 +0530 Subject: [PATCH 8/8] How to zip two collections in Java? (#2176) * How to zip two collections in Java? How to zip two collections in Java? | http://jira.baeldung.com/browse/BAEL-780 * Updated pom to add jool dependency * Added Unit Tests of Zip Collections * Moved files to libraries folder * Fixed Compilation Error * Removed jool dependency as code has been moved to libraries * Removed jool property attribute --- core-java/pom.xml | 2 +- libraries/pom.xml | 6 ++ .../baeldung/zip/ZipCollectionExample.java | 40 +++++++++ .../com/baeldung/zip/ZipCollectionTest.java | 85 +++++++++++++++++++ 4 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 libraries/src/main/java/com/baeldung/zip/ZipCollectionExample.java create mode 100644 libraries/src/test/java/com/baeldung/zip/ZipCollectionTest.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 84a56c8bc7..ee0d6b4b4a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -417,4 +417,4 @@ 2.19.1 - \ No newline at end of file + diff --git a/libraries/pom.xml b/libraries/pom.xml index a3b78f1695..0373d54429 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -349,6 +349,12 @@ java-lsh ${java-lsh.version} + + + com.google.guava + guava + 21.0 + au.com.dius pact-jvm-consumer-junit_2.11 diff --git a/libraries/src/main/java/com/baeldung/zip/ZipCollectionExample.java b/libraries/src/main/java/com/baeldung/zip/ZipCollectionExample.java new file mode 100644 index 0000000000..3df9baad69 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/zip/ZipCollectionExample.java @@ -0,0 +1,40 @@ +package com.baeldung.zip; + +import com.google.common.collect.Streams; +import org.jooq.lambda.Seq; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.IntStream; + +public class ZipCollectionExample { + static List names = Arrays.asList("John", "Jane", "Jack", "Dennis"); + + static List ages = Arrays.asList(24, 25, 27); + + public static void main(String[] args) { + // Using Streams API from Guava 21 + Streams + .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age) + .forEach(System.out::println); + + // Using native Java 8 Int Stream + IntStream + .range(0, Math.min(names.size(), ages.size())) + .mapToObj(i -> names.get(i) + ":" + ages.get(i)) + .forEach(System.out::println); + + // Using jOOL + Seq + .of("John", "Jane", "Dennis") + .zip(Seq.of(24, 25, 27)); + + Seq + .of("John", "Jane", "Dennis") + .zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y); + + Seq + .of("a", "b", "c") + .zipWithIndex(); + } +} diff --git a/libraries/src/test/java/com/baeldung/zip/ZipCollectionTest.java b/libraries/src/test/java/com/baeldung/zip/ZipCollectionTest.java new file mode 100644 index 0000000000..6f6a7b765f --- /dev/null +++ b/libraries/src/test/java/com/baeldung/zip/ZipCollectionTest.java @@ -0,0 +1,85 @@ +package com.baeldung.zip; + +import com.google.common.collect.Streams; +import org.jooq.lambda.Seq; +import org.jooq.lambda.tuple.Tuple2; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; + +public class ZipCollectionTest { + + List names; + List ages; + List expectedOutput; + + @Before + public void setUp() throws Exception { + names = Arrays.asList("John", "Jane", "Jack", "Dennis"); + ages = Arrays.asList(24, 25, 27); + expectedOutput = Arrays.asList("John:24", "Jane:25", "Jack:27"); + } + + @Test + public void zipCollectionUsingGuava21() { + List output = Streams + .zip(names.stream(), ages.stream(), (name, age) -> name + ":" + age) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingIntStream() { + List output = IntStream + .range(0, Math.min(names.size(), ages.size())) + .mapToObj(i -> names.get(i) + ":" + ages.get(i)) + .collect(Collectors.toList()); + + assertEquals(output, expectedOutput); + } + + @Test + public void zipCollectionUsingJool() { + Seq output = Seq + .of("John", "Jane", "Jack") + .zip(Seq.of(24, 25, 27), (x, y) -> x + ":" + y); + + assertEquals(output.toList(), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolTuple() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zip(Seq.of(24, 25, 27)); + + Tuple2 element1 = new Tuple2("John", 24); + Tuple2 element2 = new Tuple2("Jane", 25); + Tuple2 element3 = new Tuple2("Dennis", 27); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + + @Test + public void zipCollectionUsingJoolWithIndex() { + Seq> output = Seq + .of("John", "Jane", "Dennis") + .zipWithIndex(); + + Tuple2 element1 = new Tuple2<>("John", 0L); + Tuple2 element2 = new Tuple2<>("Jane", 1L); + Tuple2 element3 = new Tuple2<>("Dennis", 2L); + + List expectedOutput = Arrays.asList(element1, element2, element3); + assertEquals(output.collect(Collectors.toList()), expectedOutput); + } + +} \ No newline at end of file