Merge branch 'master' into BAEL-6421-PrintWriter-write-vs-print
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
package com.baeldung;
|
||||
|
||||
public class Unrelated {
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
@@ -14,22 +14,22 @@ public class OuterUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenGetNestHostFromOuter_thenGetNestHost() {
|
||||
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
||||
assertEquals(NEST_HOST_NAME, Outer.class.getNestHost().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetNestHostFromInner_thenGetNestHost() {
|
||||
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
|
||||
assertEquals(NEST_HOST_NAME, Outer.Inner.class.getNestHost().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
|
||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
|
||||
assertTrue(Outer.Inner.class.isNestmateOf(Outer.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
|
||||
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
|
||||
assertFalse(Outer.Inner.class.isNestmateOf(Unrelated.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -9,9 +9,4 @@
|
||||
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
|
||||
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
||||
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
||||
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
|
||||
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
|
||||
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
|
||||
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
|
||||
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) [[Next -->]](/core-java-modules/core-java-8-datetime-3)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
|
||||
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
|
||||
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
|
||||
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
|
||||
- [Check if a Given Time Lies Between Two Times Regardless of Date](https://www.baeldung.com/java-check-between-two-times)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-8-datetime-2)
|
||||
@@ -0,0 +1,55 @@
|
||||
<?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>core-java-8-datetime-3</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>core-java-8-datetime-3</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.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
package com.baeldung.daterangeoverlap;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.Interval;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
|
||||
public class DateRangeOverlapChecker {
|
||||
|
||||
public static boolean isOverlapUsingCalendarAndDuration(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
|
||||
+5
-9
@@ -1,20 +1,16 @@
|
||||
package com.baeldung.localdatetoiso;
|
||||
|
||||
import org.apache.commons.lang3.time.FastDateFormat;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.ISODateTimeFormat;
|
||||
|
||||
import org.apache.commons.lang3.time.FastDateFormat;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class LocalDateToISO {
|
||||
public String formatUsingDateTimeFormatter(LocalDate localDate) {
|
||||
+44
-44
@@ -1,45 +1,45 @@
|
||||
package com.baeldung.checkiftimebetweentwotimes;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CheckIfTimeBetweenTwoTimesUnitTest {
|
||||
private LocalTime startTime = LocalTime.parse("09:00:00");
|
||||
private LocalTime endTime = LocalTime.parse("17:00:00");
|
||||
private LocalTime targetTime = LocalTime.parse("12:30:00");
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
|
||||
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
|
||||
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
|
||||
Calendar startCalendar = Calendar.getInstance();
|
||||
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
|
||||
startCalendar.set(Calendar.MINUTE, 0);
|
||||
Date startTime = startCalendar.getTime();
|
||||
|
||||
Calendar endCalendar = Calendar.getInstance();
|
||||
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
|
||||
endCalendar.set(Calendar.MINUTE, 0);
|
||||
Date endTime = endCalendar.getTime();
|
||||
|
||||
Calendar targetCalendar = Calendar.getInstance();
|
||||
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
|
||||
targetCalendar.set(Calendar.MINUTE, 30);
|
||||
Date targetTime = targetCalendar.getTime();
|
||||
|
||||
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
|
||||
}
|
||||
package com.baeldung.checkiftimebetweentwotimes;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CheckIfTimeBetweenTwoTimesUnitTest {
|
||||
private LocalTime startTime = LocalTime.parse("09:00:00");
|
||||
private LocalTime endTime = LocalTime.parse("17:00:00");
|
||||
private LocalTime targetTime = LocalTime.parse("12:30:00");
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() {
|
||||
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() {
|
||||
assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() {
|
||||
Calendar startCalendar = Calendar.getInstance();
|
||||
startCalendar.set(Calendar.HOUR_OF_DAY, 9);
|
||||
startCalendar.set(Calendar.MINUTE, 0);
|
||||
Date startTime = startCalendar.getTime();
|
||||
|
||||
Calendar endCalendar = Calendar.getInstance();
|
||||
endCalendar.set(Calendar.HOUR_OF_DAY, 17);
|
||||
endCalendar.set(Calendar.MINUTE, 0);
|
||||
Date endTime = endCalendar.getTime();
|
||||
|
||||
Calendar targetCalendar = Calendar.getInstance();
|
||||
targetCalendar.set(Calendar.HOUR_OF_DAY, 12);
|
||||
targetCalendar.set(Calendar.MINUTE, 30);
|
||||
Date targetTime = targetCalendar.getTime();
|
||||
|
||||
assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
package com.baeldung.daterangeoverlap;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DateRangeOverlapCheckerUnitTest {
|
||||
|
||||
+9
-7
@@ -1,13 +1,14 @@
|
||||
package com.baeldung.localdatetoiso;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateToISOUnitTest {
|
||||
@Test
|
||||
void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){
|
||||
public void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){
|
||||
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||
|
||||
@@ -17,7 +18,7 @@ public class LocalDateToISOUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){
|
||||
public void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){
|
||||
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||
|
||||
@@ -27,17 +28,18 @@ public class LocalDateToISOUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDate_whenUsingJodaTime_thenISOFormat() {
|
||||
public void givenLocalDate_whenUsingJodaTime_thenISOFormat() {
|
||||
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||
org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 11, 6);
|
||||
|
||||
String expected = "2023-11-06T00:00:00.000Z";
|
||||
String actual = localDateToISO.formatUsingJodaTime(localDate);
|
||||
assertEquals(expected, actual);
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() {
|
||||
public void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() {
|
||||
LocalDateToISO localDateToISO = new LocalDateToISO();
|
||||
LocalDate localDate = LocalDate.of(2023, 11, 6);
|
||||
|
||||
+25
-25
@@ -1,25 +1,25 @@
|
||||
package com.baeldung.zoneoffsetandzoneidof;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ZoneOffSetAndZoneIdOfUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenOffsetDateTimeWithUTCZoneOffset_thenOffsetShouldBeUTC() {
|
||||
OffsetDateTime dateTimeWithOffset = OffsetDateTime.now(ZoneOffset.UTC);
|
||||
assertEquals(dateTimeWithOffset.getOffset(), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTimeWithUTCZoneId_thenZoneShouldBeUTC() {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
|
||||
assertEquals(zonedDateTime.getZone(), ZoneId.of("UTC"));
|
||||
}
|
||||
}
|
||||
package com.baeldung.zoneoffsetandzoneidof;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ZoneOffSetAndZoneIdOfUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenOffsetDateTimeWithUTCZoneOffset_thenOffsetShouldBeUTC() {
|
||||
OffsetDateTime dateTimeWithOffset = OffsetDateTime.now(ZoneOffset.UTC);
|
||||
assertEquals(dateTimeWithOffset.getOffset(), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZonedDateTimeWithUTCZoneId_thenZoneShouldBeUTC() {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
|
||||
assertEquals(zonedDateTime.getZone(), ZoneId.of("UTC"));
|
||||
}
|
||||
}
|
||||
@@ -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,7 @@
|
||||
=========
|
||||
|
||||
## Core Java Collections Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)
|
||||
@@ -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>
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.iteratorvsforeach;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class IteratorVsForeachUnitTest {
|
||||
|
||||
private static Stream<Arguments> listProvider() {
|
||||
return Stream.of(Arguments.of(List.of("String1", "String2", "unwanted"), List.of("String1", "String2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyCollection_whenUsingForEach_thenNoElementsAreIterated() {
|
||||
List<String> names = Collections.emptyList();
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
names.forEach(stringBuilder::append);
|
||||
assertEquals("", stringBuilder.toString());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
public void givenCollectionWithElements_whenRemovingElementDuringForEachIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
|
||||
List<String> mutableList = new ArrayList<>(input);
|
||||
// Separate collection for items to be removed
|
||||
List<String> toRemove = new ArrayList<>();
|
||||
|
||||
// Using forEach to identify items to remove
|
||||
input.forEach(item -> {
|
||||
if (item.equals("unwanted")) {
|
||||
toRemove.add(item);
|
||||
}
|
||||
});
|
||||
|
||||
// Removing the identified items from the original list
|
||||
mutableList.removeAll(toRemove);
|
||||
assertIterableEquals(expected, mutableList);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("listProvider")
|
||||
public void givenCollectionWithElements_whenRemovingElementDuringIteratorIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
|
||||
List<String> mutableList = new ArrayList<>(input);
|
||||
Iterator<String> it = mutableList.iterator();
|
||||
while (it.hasNext()) {
|
||||
String item = it.next();
|
||||
if (item.equals("unwanted")) {
|
||||
it.remove(); // Safely remove item
|
||||
}
|
||||
}
|
||||
assertIterableEquals(expected, mutableList);
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -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)
|
||||
|
||||
-59
@@ -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"));
|
||||
}
|
||||
}
|
||||
+91
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
|
||||
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
|
||||
- [Get a Path to a Resource in a Java JAR File](https://www.baeldung.com/java-get-path-resource-jar)
|
||||
- [Java InputStream vs. InputStreamReader](https://www.baeldung.com/java-inputstream-vs-inputstreamreader)
|
||||
|
||||
@@ -13,4 +13,3 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||
- [Read Multiple Inputs on the Same Line in Java](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
||||
- [Java InputStream vs. InputStreamReader](https://www.baeldung.com/java-inputstream-vs-inputstreamreader)
|
||||
|
||||
@@ -260,7 +260,6 @@
|
||||
<!-- util -->
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<mockito.version>4.6.1</mockito.version>
|
||||
<!-- maven plugins -->
|
||||
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
||||
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.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>
|
||||
|
||||
+13
@@ -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);
|
||||
}
|
||||
}
|
||||
+22
@@ -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);
|
||||
}
|
||||
}
|
||||
+21
@@ -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!");
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.symmetricsubstringlength;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SymmetricSubstringMaxLengthUnitTest {
|
||||
String input = "<><??>>";
|
||||
int expected = 4;
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingSymmetricSubstringExpansion_thenFindLongestSymmetricSubstring() {
|
||||
int start = 0;
|
||||
int mid = 0;
|
||||
int last_gt = 0;
|
||||
int end = 0;
|
||||
int best = 0;
|
||||
|
||||
while (start < input.length()) {
|
||||
int current = Math.min(mid - start, end - mid);
|
||||
if (best < current) {
|
||||
best = current;
|
||||
}
|
||||
|
||||
if (end - mid == current && end < input.length()) {
|
||||
if (input.charAt(end) == '?') {
|
||||
end++;
|
||||
} else if (input.charAt(end) == '>') {
|
||||
end++;
|
||||
last_gt = end;
|
||||
} else {
|
||||
end++;
|
||||
mid = end;
|
||||
start = Math.max(start, last_gt);
|
||||
}
|
||||
} else if (mid < input.length() && input.charAt(mid) == '?') {
|
||||
mid++;
|
||||
} else if (start < mid) {
|
||||
start++;
|
||||
} else {
|
||||
start = Math.max(start, last_gt);
|
||||
mid++;
|
||||
end = Math.max(mid, end);
|
||||
}
|
||||
}
|
||||
int result = 2 * best;
|
||||
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingBruteForce_thenFindLongestSymmetricSubstring() {
|
||||
int max = 0;
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
for (int j = i + 1; j <= input.length(); j++) {
|
||||
String t = input.substring(i, j);
|
||||
if (t.length() % 2 == 0) {
|
||||
int k = 0, l = t.length() - 1;
|
||||
boolean isSym = true;
|
||||
while (k < l && isSym) {
|
||||
if (!(t.charAt(k) == '<' || t.charAt(k) == '?') && (t.charAt(l) == '>' || t.charAt(l) == '?')) {
|
||||
isSym = false;
|
||||
}
|
||||
k++;
|
||||
l--;
|
||||
}
|
||||
if (isSym) {
|
||||
max = Math.max(max, t.length());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(expected, max);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -89,6 +89,7 @@
|
||||
<module>core-java-collections-3</module>
|
||||
<module>core-java-collections-4</module>
|
||||
<module>core-java-collections-5</module>
|
||||
<module>core-java-collections-6</module>
|
||||
<module>core-java-collections-conversions</module>
|
||||
<module>core-java-collections-set-2</module>
|
||||
<module>core-java-collections-list</module>
|
||||
|
||||
Reference in New Issue
Block a user