@@ -4,3 +4,4 @@
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||
|
||||
@@ -18,6 +18,18 @@
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -34,6 +46,7 @@
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-collections4.version>4.3</commons-collections4.version>
|
||||
<guava.version>28.0-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
public class Employee {
|
||||
|
||||
long id;
|
||||
|
||||
String name;
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(long id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Comparators;
|
||||
import com.google.common.collect.Ordering;;
|
||||
|
||||
public class SortedListChecker {
|
||||
|
||||
private SortedListChecker() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingIterativeApproach(List<String> listOfStrings) {
|
||||
if (isEmpty(listOfStrings) || listOfStrings.size() == 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Iterator<String> iter = listOfStrings.iterator();
|
||||
String current, previous = iter.next();
|
||||
while (iter.hasNext()) {
|
||||
current = iter.next();
|
||||
if (previous.compareTo(current) > 0) {
|
||||
return false;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingIterativeApproach(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||
if (isEmpty(employees) || employees.size() == 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Iterator<Employee> iter = employees.iterator();
|
||||
Employee current, previous = iter.next();
|
||||
while (iter.hasNext()) {
|
||||
current = iter.next();
|
||||
if (employeeComparator.compare(previous, current) > 0) {
|
||||
return false;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) {
|
||||
return isSortedRecursive(listOfStrings, listOfStrings.size());
|
||||
}
|
||||
|
||||
public static boolean isSortedRecursive(List<String> listOfStrings, int index) {
|
||||
if (index < 2) {
|
||||
return true;
|
||||
} else if (listOfStrings.get(index - 2)
|
||||
.compareTo(listOfStrings.get(index - 1)) > 0) {
|
||||
return false;
|
||||
} else {
|
||||
return isSortedRecursive(listOfStrings, index - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) {
|
||||
return Ordering.<String> natural()
|
||||
.isOrdered(listOfStrings);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||
return Ordering.from(employeeComparator)
|
||||
.isOrdered(employees);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) {
|
||||
return Ordering.<String> natural()
|
||||
.nullsLast()
|
||||
.isOrdered(listOfStrings);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) {
|
||||
return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder());
|
||||
}
|
||||
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SortedListCheckerUnitTest {
|
||||
|
||||
private List<String> sortedListOfString;
|
||||
private List<String> unsortedListOfString;
|
||||
private List<String> singletonList;
|
||||
|
||||
private List<Employee> employeesSortedByName;
|
||||
private List<Employee> employeesNotSortedByName;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
|
||||
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
|
||||
singletonList = Collections.singletonList("NY");
|
||||
|
||||
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
|
||||
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -29,6 +29,12 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.auto.service</groupId>
|
||||
<artifactId>auto-service</artifactId>
|
||||
<version>${auto-service.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
@@ -40,6 +46,7 @@
|
||||
<properties>
|
||||
<auto-value.version>1.3</auto-value.version>
|
||||
<auto-factory.version>1.0-beta5</auto-factory.version>
|
||||
<auto-service.version>1.0-rc5</auto-service.version>
|
||||
<guice.version>4.2.0</guice.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.autoservice;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@AutoService(TranslationService.class)
|
||||
public class BingTranslationServiceProvider implements TranslationService {
|
||||
@Override
|
||||
public String translate(String message, Locale from, Locale to) {
|
||||
// implementation details
|
||||
return message + " (translated by Bing)";
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.autoservice;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
@AutoService(TranslationService.class)
|
||||
public class GoogleTranslationServiceProvider implements TranslationService {
|
||||
@Override
|
||||
public String translate(String message, Locale from, Locale to) {
|
||||
// implementation details
|
||||
return message + " (translated by Google)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.autoservice;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public interface TranslationService {
|
||||
String translate(String message, Locale from, Locale to);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.autoservice;
|
||||
|
||||
import com.baeldung.autoservice.TranslationService;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ServiceLoader;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TranslationServiceUnitTest {
|
||||
|
||||
private ServiceLoader<TranslationService> loader;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
loader = ServiceLoader.load(TranslationService.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceLoaderLoads_thenLoadsAllProviders() {
|
||||
long count = StreamSupport.stream(loader.spliterator(), false).count();
|
||||
assertEquals(2, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() {
|
||||
TranslationService googleService = StreamSupport.stream(loader.spliterator(), false)
|
||||
.filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider"))
|
||||
.findFirst()
|
||||
.get();
|
||||
|
||||
String message = "message";
|
||||
assertEquals(message + " (translated by Google)", googleService.translate(message, null, null));
|
||||
}
|
||||
}
|
||||
@@ -5,4 +5,5 @@
|
||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.forEach;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
class ReverseList extends ArrayList<String> {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Consumer<String> removeElement = s -> {
|
||||
System.out.println(s + " " + list.size());
|
||||
if (s != null && s.equals("A")) {
|
||||
list.remove("D");
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public Iterator<String> iterator() {
|
||||
|
||||
final int startIndex = this.size() - 1;
|
||||
final List<String> list = this;
|
||||
return new Iterator<String>() {
|
||||
|
||||
int currentIndex = startIndex;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return currentIndex >= 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String next() {
|
||||
String next = list.get(currentIndex);
|
||||
currentIndex--;
|
||||
return next;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void forEach(Consumer<? super String> action) {
|
||||
for (String s : this) {
|
||||
action.accept(s);
|
||||
}
|
||||
}
|
||||
|
||||
public void iterateParallel() {
|
||||
list.forEach(System.out::print);
|
||||
System.out.print(" ");
|
||||
list.parallelStream().forEach(System.out::print);
|
||||
}
|
||||
|
||||
public void iterateReverse() {
|
||||
List<String> myList = new ReverseList();
|
||||
myList.addAll(list);
|
||||
myList.forEach(System.out::print);
|
||||
System.out.print(" ");
|
||||
myList.stream().forEach(System.out::print);
|
||||
}
|
||||
|
||||
public void removeInCollectionForEach() {
|
||||
list.forEach(removeElement);
|
||||
}
|
||||
|
||||
public void removeInStreamForEach() {
|
||||
list.stream().forEach(removeElement);
|
||||
}
|
||||
|
||||
public static void main(String[] argv) {
|
||||
|
||||
ReverseList collectionForEach = new ReverseList();
|
||||
collectionForEach.iterateParallel();
|
||||
collectionForEach.iterateReverse();
|
||||
collectionForEach.removeInCollectionForEach();
|
||||
collectionForEach.removeInStreamForEach();
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class SkipLimitComparison {
|
||||
|
||||
public static void main(String[] args) {
|
||||
skipExample();
|
||||
limitExample();
|
||||
limitInfiniteStreamExample();
|
||||
getEvenNumbers(10, 10).stream()
|
||||
.forEach(System.out::println);
|
||||
}
|
||||
|
||||
public static void skipExample() {
|
||||
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.skip(2)
|
||||
.forEach(i -> System.out.print(i + " "));
|
||||
}
|
||||
|
||||
public static void limitExample() {
|
||||
Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.limit(2)
|
||||
.forEach(i -> System.out.print(i + " "));
|
||||
}
|
||||
|
||||
public static void limitInfiniteStreamExample() {
|
||||
Stream.iterate(0, i -> i + 1)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.limit(10)
|
||||
.forEach(System.out::println);
|
||||
}
|
||||
|
||||
private static List<Integer> getEvenNumbers(int offset, int limit) {
|
||||
return Stream.iterate(0, i -> i + 1)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.skip(offset)
|
||||
.limit(limit)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +1,35 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>
|
||||
<groupId>com.baeldung.exception.numberformat</groupId>
|
||||
<artifactId>core-java-exceptions</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>core-java-exceptions</name>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>
|
||||
<groupId>com.baeldung.exception.numberformat</groupId>
|
||||
<artifactId>core-java-exceptions</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>core-java-exceptions</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
package com.baeldung.error;
|
||||
package com.baeldung.exception.error;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ErrorGeneratorUnitTest {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.rawtype;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class RawTypeDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
RawTypeDemo rawTypeDemo = new RawTypeDemo();
|
||||
rawTypeDemo.methodA();
|
||||
}
|
||||
|
||||
public void methodA() {
|
||||
// parameterized type
|
||||
List<String> listStr = new ArrayList<>();
|
||||
listStr.add("Hello Folks!");
|
||||
methodB(listStr);
|
||||
String s = listStr.get(1); // ClassCastException at run time
|
||||
}
|
||||
|
||||
public void methodB(List rawList) { // Inexpressive raw type
|
||||
rawList.add(1); // Unsafe operation
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.breakloop;
|
||||
|
||||
public class LoopBreaking {
|
||||
|
||||
public String simpleBreak() {
|
||||
String result = "";
|
||||
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||
result += "outer" + outerCounter;
|
||||
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||
result += "inner" + innerCounter;
|
||||
if (innerCounter == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String labelBreak() {
|
||||
String result = "";
|
||||
myBreakLabel:
|
||||
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||
result += "outer" + outerCounter;
|
||||
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||
result += "inner" + innerCounter;
|
||||
if (innerCounter == 0) {
|
||||
break myBreakLabel;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String usingReturn() {
|
||||
String result = "";
|
||||
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
|
||||
result += "outer" + outerCounter;
|
||||
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
|
||||
result += "inner" + innerCounter;
|
||||
if (innerCounter == 0) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.breakloop;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class LoopBreakingUnitTest {
|
||||
|
||||
private LoopBreaking loopBreaking = new LoopBreaking();
|
||||
|
||||
@Test
|
||||
void whenUsingBreak_shouldBreakInnerLoop() {
|
||||
assertEquals("outer0inner0outer1inner0", loopBreaking.simpleBreak());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingLabeledBreak_shouldBreakInnerLoopAndOuterLoop() {
|
||||
assertEquals("outer0inner0", loopBreaking.labelBreak());
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingReturn_shouldBreakInnerLoopAndOuterLoop() {
|
||||
assertEquals("outer0inner0", loopBreaking.usingReturn());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>easy-random</artifactId>
|
||||
<name>easy-random</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jeasy</groupId>
|
||||
<artifactId>easy-random-core</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.easy.random.model;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
public class Department {
|
||||
private String depName;
|
||||
|
||||
public Department(String depName) {
|
||||
this.depName = depName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", Department.class.getSimpleName() + "[", "]").add("depName='" + depName + "'")
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.baeldung.easy.random.model;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private long id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Department department;
|
||||
private Collection<Employee> coworkers;
|
||||
private Map<YearQuarter, Grade> quarterGrades;
|
||||
|
||||
public Employee(long id, String firstName, String lastName, Department department) {
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Employee employee = (Employee) o;
|
||||
return id == employee.id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Department getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public Collection<Employee> getCoworkers() {
|
||||
return Collections.unmodifiableCollection(coworkers);
|
||||
}
|
||||
|
||||
public Map<YearQuarter, Grade> getQuarterGrades() {
|
||||
return Collections.unmodifiableMap(quarterGrades);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", Employee.class.getSimpleName() + "[", "]").add("id=" + id)
|
||||
.add("firstName='" + firstName + "'")
|
||||
.add("lastName='" + lastName + "'")
|
||||
.add("department=" + department)
|
||||
.add("coworkers size=" + ((coworkers == null) ? 0 : coworkers.size()))
|
||||
.add("quarterGrades=" + quarterGrades)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.baeldung.easy.random.model;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
public class Grade {
|
||||
|
||||
private int grade;
|
||||
|
||||
public Grade(int grade) {
|
||||
this.grade = grade;
|
||||
}
|
||||
|
||||
public int getGrade() {
|
||||
return grade;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", Grade.class.getSimpleName() + "[", "]").add("grade=" + grade)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.baeldung.easy.random.model;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
|
||||
public class Person {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Integer age;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]").add("firstName='" + firstName + "'")
|
||||
.add("lastName='" + lastName + "'")
|
||||
.add("age=" + age)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.baeldung.easy.random.model;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
public class YearQuarter {
|
||||
|
||||
private LocalDate startDate;
|
||||
private LocalDate endDate;
|
||||
|
||||
public YearQuarter(LocalDate startDate) {
|
||||
this.startDate = startDate;
|
||||
autoAdjustEndDate();
|
||||
}
|
||||
|
||||
private void autoAdjustEndDate() {
|
||||
endDate = startDate.plusMonths(3L);
|
||||
}
|
||||
|
||||
public LocalDate getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public LocalDate getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
YearQuarter quarter = (YearQuarter) o;
|
||||
return Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(startDate, endDate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringJoiner(", ", YearQuarter.class.getSimpleName() + "[", "]").add("startDate=" + startDate)
|
||||
.add("endDate=" + endDate)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.baeldung.easy.random.randomizer;
|
||||
|
||||
import org.baeldung.easy.random.model.YearQuarter;
|
||||
import org.jeasy.random.api.Randomizer;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
|
||||
public class YearQuarterRandomizer implements Randomizer<YearQuarter> {
|
||||
|
||||
private LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 25);
|
||||
|
||||
@Override
|
||||
public YearQuarter getRandomValue() {
|
||||
date = date.plusMonths(3);
|
||||
return new YearQuarter(date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package org.baeldung.easy.random;
|
||||
|
||||
import org.baeldung.easy.random.model.Employee;
|
||||
import org.baeldung.easy.random.model.Person;
|
||||
import org.baeldung.easy.random.model.YearQuarter;
|
||||
import org.baeldung.easy.random.randomizer.YearQuarterRandomizer;
|
||||
import org.jeasy.random.EasyRandom;
|
||||
import org.jeasy.random.EasyRandomParameters;
|
||||
import org.jeasy.random.FieldPredicates;
|
||||
import org.jeasy.random.TypePredicates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EasyRandomUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDefaultConfiguration_thenGenerateSingleObject() {
|
||||
EasyRandom generator = new EasyRandom();
|
||||
Person person = generator.nextObject(Person.class);
|
||||
|
||||
assertNotNull(person.getAge());
|
||||
assertNotNull(person.getFirstName());
|
||||
assertNotNull(person.getLastName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDefaultConfiguration_thenGenerateObjectsList() {
|
||||
EasyRandom generator = new EasyRandom();
|
||||
List<Person> persons = generator.objects(Person.class, 5)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(5, persons.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCustomConfiguration_thenGenerateSingleEmployee() {
|
||||
EasyRandomParameters parameters = new EasyRandomParameters();
|
||||
parameters.stringLengthRange(3, 3);
|
||||
parameters.collectionSizeRange(5, 5);
|
||||
parameters.excludeField(FieldPredicates.named("lastName").and(FieldPredicates.inClass(Employee.class)));
|
||||
parameters.excludeType(TypePredicates.inPackage("not.existing.pkg"));
|
||||
parameters.randomize(YearQuarter.class, new YearQuarterRandomizer());
|
||||
|
||||
EasyRandom generator = new EasyRandom(parameters);
|
||||
Employee employee = generator.nextObject(Employee.class);
|
||||
|
||||
assertEquals(3, employee.getFirstName().length());
|
||||
assertEquals(5, employee.getCoworkers().size());
|
||||
assertEquals(5, employee.getQuarterGrades().size());
|
||||
assertNotNull(employee.getDepartment());
|
||||
|
||||
assertNull(employee.getLastName());
|
||||
|
||||
for (YearQuarter key : employee.getQuarterGrades().keySet()) {
|
||||
assertEquals(key.getStartDate(), key.getEndDate().minusMonths(3L));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.convertiteratortolist;
|
||||
package com.baeldung.convert.iteratortolist;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user