Merge branch 'eugenp:master' into master

This commit is contained in:
Wynn Teo
2024-04-09 09:11:34 +08:00
committed by GitHub
220 changed files with 5968 additions and 948 deletions
@@ -13,4 +13,22 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<jmh.version>1.35</jmh.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,50 @@
package com.baeldung.algorithms.perfectnumber;
import java.util.stream.IntStream;
class PerfectNumber {
public static boolean isPerfectBruteForce(int number) {
int sum = 0;
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
public static boolean isPerfectStream(int number) {
int sum = IntStream.rangeClosed(2, (int) Math.sqrt(number))
.filter(test -> number % test == 0)
.reduce(1, (s, test) -> s + test + (number / test));
return sum == number;
}
public static boolean isPerfectEuclidEuler(int number) {
int p = 2;
int perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (int) (Math.pow(2, p - 1) * (Math.pow(2, p) - 1));
}
return false;
}
public static boolean isPerfectEuclidEulerUsingShift(int number) {
int p = 2;
int perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
while (perfectNumber <= number) {
if (perfectNumber == number) {
return true;
}
p++;
perfectNumber = (2 << (p - 1)) * ((2 << p) - 1);
}
return false;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.algorithms.perfectnumber;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@State(Scope.Benchmark)
public class PerfectNumberBenchmark {
@Benchmark
public boolean bruteForceBenchmark() {
return PerfectNumber.isPerfectBruteForce(33550336);
}
@Benchmark
public boolean streamBenchmark() {
return PerfectNumber.isPerfectStream(33550336);
}
@Benchmark
public boolean euclidEulerBenchmark() {
return PerfectNumber.isPerfectEuclidEuler(33550336);
}
@Benchmark
public boolean euclidEulerUsingShiftBenchmark() {
return PerfectNumber.isPerfectEuclidEulerUsingShift(33550336);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(PerfectNumberBenchmark.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();
}
}
@@ -0,0 +1,68 @@
package com.baeldung.algorithms.perfectnumber;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PerfectNumberUnitTest {
@Test
void givenPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectBruteForce(6));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectBruteForce(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectBruteForce_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectBruteForce(-28));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectStream_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectStream(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectStream(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectStream_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectStream(-6));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectEuclidEuler(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEuler(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectEuclidEuler_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEuler(-6));
}
@Test
void givenPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnTrue() {
assertTrue(PerfectNumber.isPerfectEuclidEulerUsingShift(28));
}
@Test
void givenNonPerfectNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(10));
}
@Test
void givenNegativeNumber_whenCheckingIsPerfectEuclidEulerUsingShift_thenReturnFalse() {
assertFalse(PerfectNumber.isPerfectEuclidEulerUsingShift(-6));
}
}
@@ -9,7 +9,6 @@
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
@@ -55,8 +55,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
@@ -0,0 +1,5 @@
=========
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-6</artifactId>
<packaging>jar</packaging>
<name>core-java-collections-6</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.roaringbitmap</groupId>
<artifactId>RoaringBitmap</artifactId>
<version>${roaringbitmap.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<junit.version>5.9.2</junit.version>
<roaringbitmap.version>0.9.38</roaringbitmap.version>
<jmh.version>1.36</jmh.version>
</properties>
</project>
@@ -0,0 +1,71 @@
package com.baeldung.listiteration;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
public class ListIterationUnitTest {
List<String> programmingLanguages = new ArrayList<>(List.of("Java", "Python", "C++"));
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
@Test
public void givenStringList_whenAddElementWithListIterator_thenModifiedList() {
ListIterator<String> listIterator = programmingLanguages.listIterator();
while (listIterator.hasNext()) {
String language = listIterator.next();
if (language.equals("Python")) {
listIterator.add("JavaScript");
}
}
assertIterableEquals(Arrays.asList("Java", "Python", "JavaScript", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyElementWithListIterator_thenModifiedList() {
ListIterator<Integer> listIterator = numbers.listIterator();
while (listIterator.hasNext()) {
int num = listIterator.next();
if (num == 2) {
listIterator.add(num * 10);
}
}
assertIterableEquals(Arrays.asList(1, 2, 20, 3), numbers);
}
@Test
public void givenStringList_whenAddElementWithEnhancedForLoopAndCopy_thenModifiedList() {
List<String> copyOfWords = new ArrayList<>(programmingLanguages);
for (String word : copyOfWords) {
programmingLanguages.add(word.toUpperCase()); // Modified: Convert to uppercase
}
assertIterableEquals(Arrays.asList("Java", "Python", "C++", "JAVA", "PYTHON", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyElementWithEnhancedForLoopAndCopy_thenModifiedList() {
List<Integer> copyOfNumbers = new ArrayList<>(numbers);
for (int num : copyOfNumbers) {
numbers.add(num * 2);
}
assertIterableEquals(Arrays.asList(1, 2, 3, 2, 4, 6), numbers);
}
@Test
public void givenStringList_whenConvertToUpperCaseWithJava8Stream_thenModifiedList() {
programmingLanguages = programmingLanguages.stream().map(String::toUpperCase).collect(Collectors.toList());
assertIterableEquals(Arrays.asList("JAVA", "PYTHON", "C++"), programmingLanguages);
}
@Test
public void givenNumericalList_whenMultiplyByThreeWithJava8Stream_thenModifiedList() {
numbers = numbers.stream().map(num -> num * 3).collect(Collectors.toList());
assertIterableEquals(Arrays.asList(3, 6, 9), numbers);
}
}
@@ -5,3 +5,4 @@ This module contains articles about conversions among Collection types in Java.
### Relevant Articles:
- [Converting HashMap Values to an ArrayList in Java](https://www.baeldung.com/java-hashmap-arraylist)
- [Joining a List<String> in Java With Commas and “and”](https://www.baeldung.com/java-string-concatenation-natural-language)
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
@@ -1,59 +0,0 @@
package com.baeldung.java.listInitialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
import org.junit.Test;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
Assert.assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
Assert.assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArraysAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
Assert.assertEquals("baz", list.get(0));
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
Assert.assertTrue(list.contains("foo"));
}
}
@@ -0,0 +1,91 @@
package com.baeldung.java.listinitialization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import lombok.extern.java.Log;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArraysAsList_whenUsingArrayListConstructor_thenWeCanAddOrRemove() {
List<String> list = new ArrayList<>(Arrays.asList("foo", "bar"));
list.add("baz");
assertEquals(List.of("foo", "bar","baz"), list);
list.remove("baz");
assertEquals(List.of("foo", "bar"), list);
}
@Test
public void givenArraysAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
assertEquals("baz", list.get(0));
}
@Test
public void givenIntNumbers_whenRequiredLong_thenCastAutomatically() {
int intNum = 42;
long longNum = intNum;
assertEquals(42L, longNum);
}
@Test
public void givenArrayAsList_whenRequiredLongList_thenGetExpectedResult() {
List<Long> listOfLongFixedSize = Arrays.asList(1L, 2L, 3L);
List<Long> listOfLong = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
List<Long> expected = List.of(1L, 2L, 3L);
assertEquals(expected, listOfLongFixedSize);
assertEquals(expected, listOfLong);
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
assertTrue(list.contains("foo"));
}
}
@@ -86,7 +86,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<jcabi-aspects.version>0.22.6</jcabi-aspects.version>
<aspectjrt.version>1.9.20.1</aspectjrt.version>
<cactoos.version>0.43</cactoos.version>
<cactoos.version>0.55.0</cactoos.version>
<ea-async.version>1.2.3</ea-async.version>
<jcabi-maven-plugin.version>0.14.1</jcabi-maven-plugin.version>
<aspectjtools.version>1.9.20.1</aspectjtools.version>
@@ -7,15 +7,11 @@
- [Evaluating a Math Expression in Java](https://www.baeldung.com/java-evaluate-math-expression-string)
- [Swap Two Variables in Java](https://www.baeldung.com/java-swap-two-variables)
- [Java Program to Find the Roots of a Quadratic Equation](https://www.baeldung.com/roots-quadratic-equation)
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascal’s Triangle](https://www.baeldung.com/java-pascal-triangle)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)
- [Validate if a String Is a Valid Geo Coordinate](https://www.baeldung.com/java-geo-coordinates-validation)
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
- [Calculating the Power of Any Number in Java Without Using Math pow() Method](https://www.baeldung.com/java-calculating-the-power-without-math-pow)
- [Solving Rod Cutting Problem in Java](https://www.baeldung.com/java-rod-cutting-problem)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
@@ -2,3 +2,7 @@
### Relevant articles:
- [Calculate Percentiles in Java](https://www.baeldung.com/java-compute-percentiles)
- [Solving Rod Cutting Problem in Java](https://www.baeldung.com/java-rod-cutting-problem)
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)
@@ -12,4 +12,8 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<java.version>17</java.version>
</properties>
</project>
@@ -0,0 +1,13 @@
package com.baeldung.passclassasparameter;
public class Example {
public static void processClass(Class<?> clazz) {
System.out.println("Processing class: " + clazz.getName());
}
public static void main(String[] args) {
processClass(String.class);
processClass(Integer.class);
processClass(Double.class);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.passclassasparameter;
import java.util.ArrayList;
import java.util.List;
public class GenericExample {
public static <T> void printListElements(Class<T> clazz, List<T> list) {
System.out.println("Elements of " + clazz.getSimpleName() + " list:");
for (T element : list) {
System.out.println(element);
}
}
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Java");
stringList.add("is");
stringList.add("awesome");
printListElements(String.class, stringList);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.passclassasparameter;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void processClass(Class<?> clazz, String methodName) throws Exception {
Method method = clazz.getMethod(methodName);
Object instance = clazz.getDeclaredConstructor().newInstance();
method.invoke(instance);
}
public static void main(String[] args) throws Exception {
processClass(ReflectionTarget.class, "sayHello");
}
}
class ReflectionTarget {
public void sayHello() {
System.out.println("Hello, Reflection!");
}
}
@@ -0,0 +1,43 @@
import java.util.Map;
public class UseHashMapToConvertPhoneNumberInWordsToNumber {
private static Map<String, Integer> multipliers = Map.of("double",2,
"triple", 3,
"quadruple", 4);
private static Map<String, String> digits = Map.of("zero","1",
"one", "1",
"two", "2",
"three", "3",
"four", "4",
"five", "5",
"six", "6",
"seven", "7",
"eight", "8",
"nine", "9");
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
StringBuilder output = new StringBuilder();
Integer currentMultiplier = null;
String[] words = phoneNumberInWord.split(" ");
for (String word : words) {
Integer multiplier = multipliers.get(word);
if (multiplier != null) {
if (currentMultiplier != null) {
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
}
currentMultiplier = multiplier;
} else {
String digit = digits.get(word);
if (digit == null) {
throw new IllegalArgumentException("Invalid word: " + word);
}
output.append(digit.repeat(currentMultiplier != null ? currentMultiplier : 1));
currentMultiplier = null;
}
}
return output.toString();
}
}
@@ -0,0 +1,64 @@
public class UseSwitchToConvertPhoneNumberInWordsToNumber {
public static String convertPhoneNumberInWordsToNumber(String phoneNumberInWord) {
StringBuilder output = new StringBuilder();
Integer currentMultiplier = null;
String[] words = phoneNumberInWord.split(" ");
for (String word : words) {
Integer multiplier = getWordAsMultiplier(word);
if (multiplier != null) {
if (currentMultiplier != null) {
throw new IllegalArgumentException("Cannot have consecutive multipliers, at: " + word);
}
currentMultiplier = multiplier;
} else {
output.append(getWordAsDigit(word).repeat(currentMultiplier != null ? currentMultiplier : 1));
currentMultiplier = null;
}
}
return output.toString();
}
public static Integer getWordAsMultiplier(String word) {
switch (word) {
case "double":
return 2;
case "triple":
return 3;
case "quadruple":
return 4;
default:
return null;
}
}
public static String getWordAsDigit(String word) {
switch (word) {
case "zero":
return "0";
case "one":
return "1";
case "two":
return "2";
case "three":
return "3";
case "four":
return "4";
case "five":
return "5";
case "six":
return "6";
case "seven":
return "7";
case "eight":
return "8";
case "nine":
return "9";
default:
throw new IllegalArgumentException("Invalid word: " + word);
}
}
}

Some files were not shown because too many files have changed in this diff Show More