From 017d8d2e8b20a700497f764c7cf588d0628312ea Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 22 Dec 2019 22:33:54 +0100 Subject: [PATCH 1/8] BAEL-19890: Upgrade to Spring Boot 2.2.2 and refactor test method --- spring-5-reactive-security/pom.xml | 2 +- ...ployeeSpringFunctionalIntegrationTest.java | 32 ++++++++----------- 2 files changed, 14 insertions(+), 20 deletions(-) diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 2f4a31241b..58c993bda5 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -128,7 +128,7 @@ 1.0 4.1 3.1.6.RELEASE - 2.2.1.RELEASE + 2.2.2.RELEASE diff --git a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java index 6e73e8072c..d8e2f0b23b 100644 --- a/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -1,11 +1,7 @@ package com.baeldung.reactive.functional; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -import java.util.ArrayList; -import java.util.List; - +import com.baeldung.webflux.Employee; +import com.baeldung.webflux.EmployeeRepository; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,13 +11,15 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; - -import com.baeldung.webflux.Employee; -import com.baeldung.webflux.EmployeeRepository; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -58,15 +56,11 @@ public class EmployeeSpringFunctionalIntegrationTest { .bindToRouterFunction(config.getAllEmployeesRoute()) .build(); - List employeeList = new ArrayList<>(); + List employees = Arrays.asList( + new Employee("1", "Employee 1"), + new Employee("2", "Employee 2")); - Employee employee1 = new Employee("1", "Employee 1"); - Employee employee2 = new Employee("2", "Employee 2"); - - employeeList.add(employee1); - employeeList.add(employee2); - - Flux employeeFlux = Flux.fromIterable(employeeList); + Flux employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() @@ -75,7 +69,7 @@ public class EmployeeSpringFunctionalIntegrationTest { .expectStatus() .isOk() .expectBodyList(Employee.class) - .isEqualTo(employeeList); + .isEqualTo(employees); } @Test From 531b01ec863b04b9010d739ed572478bdc94933b Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sat, 28 Dec 2019 22:34:21 +0100 Subject: [PATCH 2/8] BAEL-3180: Simplify spring-aop tests --- .../main/java/com/baeldung/Application.java | 1 - .../springAop-applicationContext.xml | 106 +++++++++--------- .../test/java/com/baeldung/TestConfig.java | 11 -- .../AopLoggingIntegrationTest.java | 4 +- .../AopPerformanceIntegrationTest.java | 4 +- .../AopPublishingIntegrationTest.java | 4 +- 6 files changed, 59 insertions(+), 71 deletions(-) rename spring-aop/src/main/resources/{org.baeldung.logger => com.baeldung.logger}/springAop-applicationContext.xml (98%) delete mode 100644 spring-aop/src/test/java/com/baeldung/TestConfig.java diff --git a/spring-aop/src/main/java/com/baeldung/Application.java b/spring-aop/src/main/java/com/baeldung/Application.java index 52ef79ac23..c0490d50c6 100644 --- a/spring-aop/src/main/java/com/baeldung/Application.java +++ b/spring-aop/src/main/java/com/baeldung/Application.java @@ -6,7 +6,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml similarity index 98% rename from spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml rename to spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml index 32e50e3502..595e7e46e6 100644 --- a/spring-aop/src/main/resources/org.baeldung.logger/springAop-applicationContext.xml +++ b/spring-aop/src/main/resources/com.baeldung.logger/springAop-applicationContext.xml @@ -1,54 +1,54 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-aop/src/test/java/com/baeldung/TestConfig.java b/spring-aop/src/test/java/com/baeldung/TestConfig.java deleted file mode 100644 index e5db2508e4..0000000000 --- a/spring-aop/src/test/java/com/baeldung/TestConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.pointcutadvice" }) -@EnableAspectJAutoProxy -public class TestConfig { -} diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java index eff3d2eb19..a687eec388 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopLoggingIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopLoggingIntegrationTest { @Before diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java index 452609d730..5a7797e5cd 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPerformanceIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import org.junit.Before; import org.junit.Test; @@ -23,7 +23,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPerformanceIntegrationTest { @Before diff --git a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java index 559dc52cb5..996b56d61e 100644 --- a/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java +++ b/spring-aop/src/test/java/com/baeldung/pointcutadvice/AopPublishingIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung.pointcutadvice; -import com.baeldung.TestConfig; +import com.baeldung.Application; import com.baeldung.pointcutadvice.dao.FooDao; import com.baeldung.pointcutadvice.events.FooCreationEventListener; import org.junit.Before; @@ -21,7 +21,7 @@ import java.util.regex.Pattern; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {Application.class}, loader = AnnotationConfigContextLoader.class) public class AopPublishingIntegrationTest { @Before From 70aa0ba234dd7a3efded14dbf66d20ccb094918a Mon Sep 17 00:00:00 2001 From: mnafshin Date: Mon, 30 Dec 2019 21:09:05 +0330 Subject: [PATCH 3/8] PowerSet generation is Java and respective unit tests are added (BAEL-3417) (#8284) * PowerSet generation is Java and respective unit tests are added * function name is adjusted to the actual ordering name (Reverse Lexicographical ordering) * Guava example test function is changed * LazyLoad powerSet (based on Guava implementation) is added * set is used instead of map.keySet() --- .../baeldung/powerset/PowerSetUtility.java | 320 ++++++++++++++++++ .../powerset/PowerSetUtilityUnitTest.java | 225 ++++++++++++ 2 files changed, 545 insertions(+) create mode 100644 core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java create mode 100644 core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java new file mode 100644 index 0000000000..fd4c1933f6 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/powerset/PowerSetUtility.java @@ -0,0 +1,320 @@ +package com.baeldung.powerset; + +import com.google.common.collect.Sets; + +import javax.annotation.Nullable; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +public class PowerSetUtility { + + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + + //Lazy Load PowerSet class + private static class PowerSet extends AbstractSet> { + private Map map = new HashMap<>(); + private List reverseMap = new ArrayList<>(); + private Set set; + + public PowerSet(Set set) { + this.set = set; + initializeMap(); + } + + abstract class ListIterator implements Iterator { + + protected int position = 0; + private int size; + + public ListIterator(int size) { + this.size = size; + } + + @Override + public boolean hasNext() { + return position < size; + } + } + + static class Subset extends AbstractSet { + private Map map; + private List reverseMap; + private int mask; + + public Subset(Map map, List reverseMap, int mask) { + this.map = map; + this.reverseMap = reverseMap; + this.mask = mask; + } + + @Override + public Iterator iterator() { + return new Iterator() { + int remainingSetBits = mask; + + @Override + public boolean hasNext() { + return remainingSetBits != 0; + } + + @Override + public E next() { + int index = Integer.numberOfTrailingZeros(remainingSetBits); + if (index == 32) { + throw new NoSuchElementException(); + } + remainingSetBits &= ~(1 << index); + return reverseMap.get(index); + } + }; + } + + @Override + public int size() { + return Integer.bitCount(mask); + } + + @Override + public boolean contains(@Nullable Object o) { + Integer index = map.get(o); + return index != null && (mask & (1 << index)) != 0; + } + } + + @Override + public Iterator> iterator() { + return new ListIterator>(this.size()) { + @Override + public Set next() { + return new Subset<>(map, reverseMap, position++); + } + }; + } + + @Override + public int size() { + return (1 << this.set.size()); + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof Set) { + Set set = (Set) obj; + return reverseMap.containsAll(set); + } + return false; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof PowerSet) { + PowerSet that = (PowerSet) obj; + return set.equals(that.set);//Set equals check to have the same element regardless of the order of the items + } + return super.equals(obj); + } + + + private void initializeMap() { + int mapId = 0; + for (E c : this.set) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + } + + public Set> lazyLoadPowerSet(Set set) { + return new PowerSet<>(set); + } + + public Set> recursivePowerSet(Set set) { + if (set.isEmpty()) { + Set> ret = new HashSet<>(); + ret.add(set); + return ret; + } + + T element = set.iterator().next(); + Set subSetWithoutElement = getSubSetWithoutElement(set, element); + Set> powerSetSubSetWithoutElement = recursivePowerSet(subSetWithoutElement); + + Set> powerSetSubSetWithElement = addElementToAll(powerSetSubSetWithoutElement, element); + + Set> powerSet = new HashSet<>(); + powerSet.addAll(powerSetSubSetWithoutElement); + powerSet.addAll(powerSetSubSetWithElement); + return powerSet; + } + + public Set> recursivePowerSetIndexRepresentation(Collection set) { + initializeMap(set); + Set> powerSetIndices = recursivePowerSetIndexRepresentation(0, set.size()); + return unMapIndex(powerSetIndices); + } + + private List> iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) + subset.add(((1 << j) & i) > 0); + powerSet.add(subset); + } + return powerSet; + } + + private List> iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(int n) { + List> powerSet = new ArrayList<>(); + for (int i = 0; i < (1 << n); i++) { + List subset = new ArrayList<>(n); + for (int j = 0; j < n; j++) { + int grayEquivalent = i ^ (i >> 1); + subset.add(((1 << j) & grayEquivalent) > 0); + } + powerSet.add(subset); + } + return powerSet; + } + + public Set> recursivePowerSetBinaryRepresentation(Collection set) { + initializeMap(set); + Set> powerSetBoolean = recursivePowerSetBinaryRepresentation(0, set.size()); + return unMapBinary(powerSetBoolean); + } + + public List> iterativePowerSetByLoopOverNumbers(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbersWithReverseLexicographicalOrder(set.size()); + return unMapListBinary(sets); + } + + public List> iterativePowerSetByLoopOverNumbersMinimalChange(Set set) { + initializeMap(set); + List> sets = iterativePowerSetByLoopOverNumbersWithGrayCodeOrder(set.size()); + return unMapListBinary(sets); + } + + public static int getRankInLexicographicalOrder(List subset) { + int rank = 0; + for (int i = 0; i < subset.size(); i++) + if (subset.get(i)) + rank += (1 << (subset.size() - i - 1)); + return rank; + } + + public static List getSubsetForRankInLexicographicalOrder(int rank, int sizeOfSet) { + Boolean[] subset = new Boolean[sizeOfSet]; + for(int j = 0; j < sizeOfSet; j++) { + subset[sizeOfSet - j - 1] = ((rank & (1 << j)) > 0); + } + return Arrays.asList(subset); + } + + private Set> recursivePowerSetIndexRepresentation(int idx, int n) { + if (idx == n) { + Set> empty = new HashSet<>(); + empty.add(new HashSet<>()); + return empty; + } + Set> powerSetSubset = recursivePowerSetIndexRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(powerSetSubset); + for (Set s : powerSetSubset) { + HashSet subSetIdxInclusive = new HashSet<>(s); + subSetIdxInclusive.add(idx); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private Set> recursivePowerSetBinaryRepresentation(int idx, int n) { + if (idx == n) { + Set> powerSetOfEmptySet = new HashSet<>(); + powerSetOfEmptySet.add(Arrays.asList(new Boolean[n])); + return powerSetOfEmptySet; + } + Set> powerSetSubset = recursivePowerSetBinaryRepresentation(idx + 1, n); + Set> powerSet = new HashSet<>(); + for (List s : powerSetSubset) { + List subSetIdxExclusive = new ArrayList<>(s); + subSetIdxExclusive.set(idx, false); + powerSet.add(subSetIdxExclusive); + List subSetIdxInclusive = new ArrayList<>(s); + subSetIdxInclusive.set(idx, true); + powerSet.add(subSetIdxInclusive); + } + return powerSet; + } + + private void initializeMap(Collection collection) { + int mapId = 0; + for (T c : collection) { + map.put(c, mapId++); + reverseMap.add(c); + } + } + + private Set> unMapIndex(Set> sets) { + Set> ret = new HashSet<>(); + for (Set s : sets) { + HashSet subset = new HashSet<>(); + for (Integer i : s) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> unMapBinary(Collection> sets) { + Set> ret = new HashSet<>(); + for (List s : sets) { + HashSet subset = new HashSet<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private List> unMapListBinary(Collection> sets) { + List> ret = new ArrayList<>(); + for (List s : sets) { + List subset = new ArrayList<>(); + for (int i = 0; i < s.size(); i++) + if (s.get(i)) + subset.add(reverseMap.get(i)); + ret.add(subset); + } + return ret; + } + + private Set> addElementToAll(Set> powerSetSubSetWithoutElement, T element) { + Set> powerSetSubSetWithElement = new HashSet<>(); + for (Set subsetWithoutElement : powerSetSubSetWithoutElement) { + Set subsetWithElement = new HashSet<>(subsetWithoutElement); + subsetWithElement.add(element); + powerSetSubSetWithElement.add(subsetWithElement); + } + return powerSetSubSetWithElement; + } + + private Set getSubSetWithoutElement(Set set, T element) { + Set subsetWithoutElement = new HashSet<>(); + for (T s : set) { + if (!s.equals(element)) + subsetWithoutElement.add(s); + } + return subsetWithoutElement; + } +} diff --git a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java new file mode 100644 index 0000000000..0a20c36692 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/powerset/PowerSetUtilityUnitTest.java @@ -0,0 +1,225 @@ +package com.baeldung.powerset; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.hamcrest.collection.IsCollectionWithSize; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +public class PowerSetUtilityUnitTest { + + @Test + public void givenSet_WhenGuavaLibraryGeneratePowerSet_ThenItContainsAllSubsets() { + ImmutableSet set = ImmutableSet.of("APPLE", "ORANGE", "MANGO"); + Set> powerSet = Sets.powerSet(set); + Assertions.assertEquals((1 << set.size()), powerSet.size()); + MatcherAssert.assertThat(powerSet, Matchers.containsInAnyOrder( + ImmutableSet.of(), + ImmutableSet.of("APPLE"), + ImmutableSet.of("ORANGE"), + ImmutableSet.of("APPLE", "ORANGE"), + ImmutableSet.of("MANGO"), + ImmutableSet.of("APPLE", "MANGO"), + ImmutableSet.of("ORANGE", "MANGO"), + ImmutableSet.of("APPLE", "ORANGE", "MANGO") + )); + } + + @Test + public void givenSet_WhenPowerSetIsLazyLoadGenerated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + Set> powerSet = new PowerSetUtility().lazyLoadPowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculated_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSet(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByIndexRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetIndexRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedRecursiveByBinaryRepresentation_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + Set> powerSet = new PowerSetUtility().recursivePowerSetBinaryRepresentation(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (Set subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbers_ThenItContainsAllSubsets() { + Set set = RandomSetOfStringGenerator.generateRandomSet(); + + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbers(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + } + + @Test + public void givenSet_WhenPowerSetIsCalculatedIterativePowerSetByLoopOverNumbersMinimalChange_ThenItContainsAllSubsetsInGrayOrder() { + + Set set = RandomSetOfStringGenerator.generateRandomSet(); + List> powerSet = new PowerSetUtility().iterativePowerSetByLoopOverNumbersMinimalChange(set); + + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << set.size()))); + //To make sure that number of occurrence of each element is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (String name : subset) { + int num = counter.getOrDefault(name, 0); + counter.put(name, num + 1); + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (set.size() - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + //To make sure that each element in each subset is occurred once + for (List subset : powerSet) { + Assertions.assertEquals(subset.size(), new HashSet<>(subset).size()); + } + //To make sure that difference of consecutive subsets is exactly 1 + for(int i=1; i 0); + } + Assertions.assertEquals(i, PowerSetUtility.getRankInLexicographicalOrder(Arrays.asList(subset))); + } + } + + @Test + public void givenRanking_WhenPowerSetIsInLexicographicalOrder_ReturnTheSubset() { + int n = new Random().nextInt(5) + 5; //a number in [5, 10) + List> powerSet = new ArrayList<>(); + for(int i = 0; i < (1 << n); i++) { + powerSet.add(PowerSetUtility.getSubsetForRankInLexicographicalOrder(i, n)); + } + //To make sure that the size of power set is (2 power n) + MatcherAssert.assertThat(powerSet, IsCollectionWithSize.hasSize((1 << n))); + //To make sure that number of occurrence of each index is (2 power n-1) + Map counter = new HashMap<>(); + for (List subset : powerSet) { + for (int i = 0; i < subset.size(); i++) { + if(subset.get(i)) { + int num = counter.getOrDefault(i, 0); + counter.put(i, num + 1); + } + } + } + counter.forEach((k, v) -> Assertions.assertEquals((1 << (n - 1)), v.intValue())); + //To make sure that one subset is not generated twice + Assertions.assertEquals(powerSet.size(), new HashSet<>(powerSet).size()); + } + + static class RandomSetOfStringGenerator { + private static List fruits = Arrays.asList("Apples", "Avocados", "Banana", "Blueberry", "Cherry", "Clementine", "Cucumber", "Date", "Fig", + "Grapefruit"/*, "Grape", "Kiwi", "Lemon", "Mango", "Mulberry", "Melon", "Nectarine", "Olive", "Orange"*/); + + static Set generateRandomSet() { + Set set = new HashSet<>(); + Random random = new Random(); + int size = random.nextInt(fruits.size()); + while (set.size() != size) { + set.add(fruits.get(random.nextInt(fruits.size()))); + } + return set; + } + } +} From ce26810b4abfc4456ba698714d63c38188a6d446 Mon Sep 17 00:00:00 2001 From: rohitchaudhary2023 <57285851+rohitchaudhary2023@users.noreply.github.com> Date: Wed, 1 Jan 2020 02:52:53 +0530 Subject: [PATCH 4/8] BAEL-3380 (#8454) * initial commit * changes for articlesBAEL-3380 * Removed evaluation article files * BAEL-3380 * adding test case BAEL-3380 * BAEL-3380 * BAEL-3380 - updated tests and removed main class * BAEL-3380 - Updated Test class name * BAEL-3380 - Updated Test class name * BAEL-3380 - Updated testcase names as per BDD naming convention * BAEL 3380 - Added JMH benchmark --- core-java-modules/core-java-arrays-2/pom.xml | 35 +++++++++ .../arraysort/ArraySortingBenchmark.java | 72 +++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml index 3f6b7094bb..532f0a6144 100644 --- a/core-java-modules/core-java-arrays-2/pom.xml +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -19,6 +19,16 @@ org.apache.commons commons-lang3 ${commons-lang3.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} @@ -37,9 +47,34 @@ true + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.0 + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + + + 1.19 3.9 diff --git a/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java new file mode 100644 index 0000000000..640d729020 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/arraysort/ArraySortingBenchmark.java @@ -0,0 +1,72 @@ +package com.baeldung.arraysort; + +import java.util.Arrays; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 5) +@Measurement(iterations = 10) +@Fork(2) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class ArraySortingBenchmark { + + @State(Scope.Benchmark) + public static class ArrayContainer { + + @Param({ "1000", "10000", "100000", "1000000" }) + int arraySize; + + // initial unsorted array + int[] unsortedArray; + + //cloned array to sort + int[] arrayToSort; + + @Setup(Level.Trial) + public void createUnSortedArray() { + unsortedArray = new int[arraySize]; + for (int i = 0; i < arraySize; i++) { + unsortedArray[i] = new Random().nextInt(1000); + } + } + + @Setup(Level.Invocation) + public void createUnSortedArrayCopy() { + arrayToSort = unsortedArray.clone(); + } + + int[] getArrayToSort() { + return arrayToSort; + } + } + + @Benchmark + public void benchmark_arrays_parallel_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.parallelSort(arr); + b.consume(arr); + } + + @Benchmark + public void benchmark_arrays_sort(ArrayContainer d, Blackhole b) { + int[] arr = d.getArrayToSort(); + Arrays.sort(arr); + b.consume(arr); + } + +} From 888539b06d17ee19b1563959083bdab389d30bf0 Mon Sep 17 00:00:00 2001 From: rahulgul8 Date: Wed, 1 Jan 2020 16:41:12 +0530 Subject: [PATCH 5/8] Changes for "Guide to finally in Java" (BAEL-3526) (#8237) * Adding files for finally keyword * Adding returnFromCatch example. * Adding empty braces instead of dangling ; * Return from try, removing the catch block. * moving to to core-java module * moving to core-java-lang-2 --- .../finallykeyword/FinallyExample.java | 14 +++++ .../finallykeyword/FinallyExecutedCases.java | 53 ++++++++++++++++++ .../FinallyNotExecutedCases.java | 54 +++++++++++++++++++ .../PitfallsWhenUsingFinally.java | 33 ++++++++++++ .../PitfallsWhenUsingFinallyUnitTest.java | 27 ++++++++++ 5 files changed, 181 insertions(+) create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java new file mode 100644 index 0000000000..bb0bad8cf4 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExample.java @@ -0,0 +1,14 @@ +package com.baeldung.finallykeyword; + +public class FinallyExample { + + public void printCount(String count) { + try { + System.out.println("The count is " + Integer.parseInt(count)); + } catch (NumberFormatException e) { + System.out.println("No count"); + } finally { + System.out.println("In finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java new file mode 100644 index 0000000000..68a3763da0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyExecutedCases.java @@ -0,0 +1,53 @@ +package com.baeldung.finallykeyword; + +public class FinallyExecutedCases { + + public void noExceptionFinally() { + try { + System.out.println("Inside try"); + } finally { + System.out.println("Inside finally"); + } + } + + public void unhandledException() throws Exception { + try { + System.out.println("Inside try"); + throw new Exception(); + } finally { + System.out.println("Inside finally"); + } + } + + public void handledException() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromTry() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + } + } + + public String returnFromCatch() { + try { + System.out.println("Inside try"); + throw new Exception(); + } catch (Exception e) { + System.out.println("Inside catch"); + return "from catch"; + } finally { + System.out.println("Inside finally"); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java new file mode 100644 index 0000000000..92c0ea729d --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/FinallyNotExecutedCases.java @@ -0,0 +1,54 @@ +package com.baeldung.finallykeyword; + +public class FinallyNotExecutedCases { + + public void callingSystemExit() { + try { + System.out.println("Inside try"); + System.exit(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void callingRuntimeHalt() { + try { + System.out.println("Inside try"); + Runtime.getRuntime() + .halt(1); + } finally { + System.out.println("Inside finally"); + } + } + + public void infiniteLoop() { + try { + System.out.println("Inside try"); + while (true) { + } + } finally { + System.out.println("Inside finally"); + } + } + + public void daemonThread() throws InterruptedException { + Runnable runnable = () -> { + try { + System.out.println("Inside try"); + } finally { + try { + Thread.sleep(1000); + System.out.println("Inside finally"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }; + Thread regular = new Thread(runnable); + Thread daemon = new Thread(runnable); + daemon.setDaemon(true); + regular.start(); + Thread.sleep(300); + daemon.start(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java new file mode 100644 index 0000000000..f1a56441f2 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinally.java @@ -0,0 +1,33 @@ +package com.baeldung.finallykeyword; + +public class PitfallsWhenUsingFinally { + + public String disregardsUnCaughtException() { + try { + System.out.println("Inside try"); + throw new RuntimeException(); + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String ignoringOtherReturns() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + System.out.println("Inside finally"); + return "from finally"; + } + } + + public String throwsException() { + try { + System.out.println("Inside try"); + return "from try"; + } finally { + throw new RuntimeException(); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java new file mode 100644 index 0000000000..7e7a7241ec --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/finallykeyword/PitfallsWhenUsingFinallyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.finallykeyword; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class PitfallsWhenUsingFinallyUnitTest { + + PitfallsWhenUsingFinally instance = new PitfallsWhenUsingFinally(); + + @Test + public void testIgnoresException() { + String result = instance.disregardsUnCaughtException(); + assertEquals("from finally", result); + } + + @Test + public void testIgnoresOtherReturns() { + String result = instance.ignoringOtherReturns(); + assertEquals("from finally", result); + } + + @Test(expected = RuntimeException.class) + public void testThrowsException() { + instance.throwsException(); + } +} From e0f885a467973fc4210cf7511d56ab08a4664a17 Mon Sep 17 00:00:00 2001 From: M-Abdelbaset <31687750+M-Abdelbaset@users.noreply.github.com> Date: Wed, 1 Jan 2020 13:19:04 +0200 Subject: [PATCH 6/8] Bael 3510-method multiple return values (#8348) * init * first draft * first review round changes * second review round * changing arg name --- .../Coordinates.java | 49 +++++++++++++++++++ .../MultipleReturnValuesUsingArrays.java | 27 ++++++++++ .../MultipleReturnValuesUsingCollections.java | 30 ++++++++++++ .../MultipleReturnValuesUsingContainer.java | 14 ++++++ .../MultipleReturnValuesUsingTuples.java | 17 +++++++ .../methodmultiplereturnvalues/Tuple2.java | 31 ++++++++++++ ...ltipleReturnValuesUsingArraysUnitTest.java | 25 ++++++++++ ...eReturnValuesUsingCollectionsUnitTest.java | 25 ++++++++++ ...pleReturnValuesUsingContainerUnitTest.java | 17 +++++++ ...ltipleReturnValuesUsingTuplesUnitTest.java | 31 ++++++++++++ 10 files changed, 266 insertions(+) create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java new file mode 100644 index 0000000000..4a292b9b18 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Coordinates.java @@ -0,0 +1,49 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Coordinates { + + private double longitude; + private double latitude; + private String placeName; + + public Coordinates() {} + + public Coordinates(double longitude, double latitude, String placeName) { + this.longitude = longitude; + this.latitude = latitude; + this.placeName = placeName; + } + + public double calculateDistance(Coordinates c) { + + double s1 = Math.abs(this.longitude - c.longitude); + double s2 = Math.abs(this.latitude - c.latitude); + + return Math.hypot(s1, s2); + } + + public double getLongitude() { + return longitude; + } + + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + public double getLatitude() { + return latitude; + } + + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + public String getPlaceName() { + return placeName; + } + + public void setPlaceName(String placeName) { + this.placeName = placeName; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java new file mode 100644 index 0000000000..9763422618 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArrays.java @@ -0,0 +1,27 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingArrays { + + + static double[] getCoordinatesDoubleArray() { + + double[] coordinates = new double[2]; + + coordinates[0] = 10; + coordinates[1] = 12.5; + + return coordinates; + } + + + static Number[] getCoordinatesNumberArray() { + + Number[] coordinates = new Number[2]; + + coordinates[0] = 10; //Integer + coordinates[1] = 12.5; //Double + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java new file mode 100644 index 0000000000..ccd5a4b74e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollections.java @@ -0,0 +1,30 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class MultipleReturnValuesUsingCollections { + + static List getCoordinatesList() { + + List coordinates = new ArrayList<>(); + + coordinates.add(10); + coordinates.add(12.5); + + return coordinates; + } + + static Map getCoordinatesMap() { + + Map coordinates = new HashMap<>(); + + coordinates.put("longitude", 10); + coordinates.put("latitude", 12.5); + + return coordinates; + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java new file mode 100644 index 0000000000..617f0df17c --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainer.java @@ -0,0 +1,14 @@ +package com.baeldung.methodmultiplereturnvalues; + +class MultipleReturnValuesUsingContainer { + + static Coordinates getCoordinates() { + + double longitude = 10; + double latitude = 12.5; + String placeName = "home"; + + return new Coordinates(longitude, latitude, placeName); + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java new file mode 100644 index 0000000000..59984f777e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuples.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import java.util.List; + +class MultipleReturnValuesUsingTuples { + + static Tuple2 getMostDistantPoint(List coordinatesList, + Coordinates target) { + + return coordinatesList.stream() + .map(coor -> new Tuple2<>(coor, coor.calculateDistance(target))) + .max((d1, d2) -> Double.compare(d1.getSecond(), d2.getSecond())) + .get(); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java new file mode 100644 index 0000000000..57ef20d572 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/methodmultiplereturnvalues/Tuple2.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +public class Tuple2 { + + private K first; + private V second; + + public Tuple2() {} + + public Tuple2(K first, V second) { + this.first = first; + this.second = second; + } + + public K getFirst() { + return first; + } + + public V getSecond() { + return second; + } + + public void setFirst(K first) { + this.first = first; + } + + public void setSecond(V second) { + this.second = second; + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java new file mode 100644 index 0000000000..0cf90a8879 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingArraysUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingArraysUnitTest { + + @Test + void whenUsingArrayOfDoubles_thenMultipleDoubleFieldsAreReturned() { + + double[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesDoubleArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + } + + @Test + void whenUsingArrayOfNumbers_thenMultipleNumberFieldsAreReturned() { + + Number[] coordinates = MultipleReturnValuesUsingArrays.getCoordinatesNumberArray(); + assertEquals(10, coordinates[0]); + assertEquals(12.5, coordinates[1]); + + } + +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java new file mode 100644 index 0000000000..8038601986 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingCollectionsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingCollectionsUnitTest { + + @Test + void whenUsingList_thenMultipleFieldsAreReturned() { + + List coordinates = MultipleReturnValuesUsingCollections.getCoordinatesList(); + assertEquals(Integer.valueOf(10), coordinates.get(0)); + assertEquals(Double.valueOf(12.5), coordinates.get(1)); + } + + @Test + void whenUsingMap_thenMultipleFieldsAreReturned() { + + Map coordinates = MultipleReturnValuesUsingCollections.getCoordinatesMap(); + assertEquals(Integer.valueOf(10), coordinates.get("longitude")); + assertEquals(Double.valueOf(12.5), coordinates.get("latitude")); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java new file mode 100644 index 0000000000..f7fd9bd108 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingContainerUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingContainerUnitTest { + + @Test + void whenUsingContainerClass_thenMultipleFieldsAreReturned() { + + Coordinates coordinates = MultipleReturnValuesUsingContainer.getCoordinates(); + + assertEquals(10, coordinates.getLongitude()); + assertEquals(12.5, coordinates.getLatitude()); + assertEquals("home", coordinates.getPlaceName()); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java new file mode 100644 index 0000000000..52f30286bc --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/methodmultiplereturnvalues/MultipleReturnValuesUsingTuplesUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.methodmultiplereturnvalues; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +class MultipleReturnValuesUsingTuplesUnitTest { + + @Test + void whenUsingTuple_thenMultipleFieldsAreReturned() { + + List coordinatesList = new ArrayList<>(); + coordinatesList.add(new Coordinates(1, 1, "home")); + coordinatesList.add(new Coordinates(2, 2, "school")); + coordinatesList.add(new Coordinates(3, 3, "hotel")); + + Coordinates target = new Coordinates(5, 5, "gym"); + + Tuple2 mostDistantPoint = MultipleReturnValuesUsingTuples.getMostDistantPoint(coordinatesList, target); + + assertEquals(1, mostDistantPoint.getFirst().getLongitude()); + assertEquals(1, mostDistantPoint.getFirst().getLatitude()); + assertEquals("home", mostDistantPoint.getFirst().getPlaceName()); + assertEquals(5.66, BigDecimal.valueOf(mostDistantPoint.getSecond()).setScale(2, RoundingMode.HALF_UP).doubleValue()); + + } + +} From 746a609d3fa46e3ab04932c7b4a447d5ecfd9ecf Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Wed, 1 Jan 2020 17:38:39 +0100 Subject: [PATCH 7/8] [BAEL-3524] A Guide to @Serial Annotation in Java 14 (#8433) * BAEL-1935: Synthetic Class in Java * Converted tabs to spaces * [BAEL-3524] Created project core-java-14 with @Serial demo. --- core-java-modules/core-java-14/pom.xml | 52 +++++++++++++++++++ .../com/baeldung/serial/MySerialClass.java | 50 ++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 core-java-modules/core-java-14/pom.xml create mode 100644 core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml new file mode 100644 index 0000000000..48ec627416 --- /dev/null +++ b/core-java-modules/core-java-14/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + com.baeldung + core-java-14 + 1.0.0-SNAPSHOT + core-java-14 + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + --enable-preview + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + --enable-preview + + + + + + + 14 + 14 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java new file mode 100644 index 0000000000..6a013d7b59 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/serial/MySerialClass.java @@ -0,0 +1,50 @@ +package com.baeldung.serial; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.ObjectStreamField; +import java.io.Serial; +import java.io.Serializable; + +/** + * Class showcasing the usage of the Java 14 @Serial annotation. + * + * @author Donato Rimenti + */ +public class MySerialClass implements Serializable { + + @Serial + private static final ObjectStreamField[] serialPersistentFields = null; + + @Serial + private static final long serialVersionUID = 1; + + @Serial + private void writeObject(ObjectOutputStream stream) throws IOException { + // ... + } + + @Serial + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + // ... + } + + @Serial + private void readObjectNoData() throws ObjectStreamException { + // ... + } + + @Serial + private Object writeReplace() throws ObjectStreamException { + // ... + return null; + } + + @Serial + private Object readResolve() throws ObjectStreamException { + // ... + return null; + } +} \ No newline at end of file From 8506e4cd4411d333b18fa55b559002493ce8f575 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 1 Jan 2020 21:25:07 +0200 Subject: [PATCH 8/8] Update MetaprogrammingUnitTest.groovy --- .../baeldung/metaprogramming/MetaprogrammingUnitTest.groovy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy index 8066b10f9b..780b88cbbf 100644 --- a/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy +++ b/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -58,7 +58,7 @@ class MetaprogrammingUnitTest extends GroovyTestCase { void testEmployeeExtension() { Employee emp = new Employee(age: 28) - assert emp.getYearOfBirth() == 1991 + assert emp.getYearOfBirth() == 1992 } void testJavaClassesExtensions() { @@ -115,4 +115,4 @@ class MetaprogrammingUnitTest extends GroovyTestCase { Employee employee = new Employee(1, "Norman", "Lewis", 28) employee.logEmp() } -} \ No newline at end of file +}