Merge remote-tracking branch 'upstream/master' into feature/BAEL-6695-BooleanValidation

This commit is contained in:
Niket Agrawal
2023-10-05 11:47:33 +05:30
312 changed files with 4748 additions and 848 deletions
+1 -7
View File
@@ -5,7 +5,7 @@ title: '[ISSUE] '
---
**Article and Module Links**
A link to the affected article and the affected module. The link to the module is the one in the "over on GitHub" standard phrase.
A link to the affected article and the affected module. You can find the link to the module in the Conclusion section in the "on Github" standard phase.
**Describe the Issue**
A clear and concise description of what the issue is.
@@ -30,9 +30,3 @@ If applicable, add screenshots to help explain your problem.
**Additional Context**
Add any other context about the issue here.
Note that, unfortunately, we can only help with issues that are specifically and directly related to the article - not with your own, custom application.
StackOverflow is a great place to ask more general questions.
That's primarily because we get a large number of questions and - while we do try to go through as much as everything and help wherever we can, we can't really get back to all of them.
+3
View File
@@ -0,0 +1,3 @@
## Relevant Articles
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
+1
View File
@@ -5,3 +5,4 @@
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)
+1
View File
@@ -1,2 +1,3 @@
## Relevant Articles
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)
+20 -6
View File
@@ -12,6 +12,12 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
@@ -20,14 +26,22 @@
<configuration>
<source>21</source>
<target>21</target>
<compilerArgs>--enable-preview</compilerArgs>
<!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
<debug>false</debug>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
@@ -0,0 +1,11 @@
package com.baeldung.unnamed.variables;
public record Car<T extends Engine>(String name, String color, T engine) { }
abstract class Engine { }
class GasEngine extends Engine { }
class ElectricEngine extends Engine { }
class HybridEngine extends Engine { }
@@ -0,0 +1,50 @@
package com.baeldung.unnamed.variables;
public class UnnamedPatterns {
static String getObjectsColorWithNamedPattern(Object object) {
if (object instanceof Car(String name, String color, Engine engine)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithUnnamedPattern(Object object) {
if (object instanceof Car(_, String color, _)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithSwitchAndNamedPattern(Object object) {
return switch (object) {
case Car(String name, String color, Engine engine) -> color;
default -> "No color!";
};
}
static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) {
return switch (object) {
case Car(_, String color, _) -> color;
default -> "No color!";
};
}
static String getEngineTypeWithNamedPattern(Car<?> car) {
return switch (car) {
case Car(String name, String color, GasEngine engine) -> "gas";
case Car(String name, String color, ElectricEngine engine) -> "electric";
case Car(String name, String color, HybridEngine engine) -> "hybrid";
default -> "none";
};
}
static String getEngineTypeWithUnnamedPattern(Car<?> car) {
return switch (car) {
case Car(_, _, GasEngine _) -> "gas";
case Car(_, _, ElectricEngine _) -> "electric";
case Car(_, _, HybridEngine _) -> "hybrid";
default -> "none";
};
}
}
@@ -0,0 +1,134 @@
package com.baeldung.unnamed.variables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class Transaction implements AutoCloseable {
@Override
public void close() {
System.out.println("Closed!");
}
}
public class UnnamedVariables {
static int countCarsOverLimitWithNamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var car : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static int countCarsOverLimitWithUnnamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var _ : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static void sendNotificationToCarsWithNamedVariable(Collection<Car<?>> cars) {
sendOneTimeNotification();
for (int i = 0; i < cars.size(); i++) {
// Notify car
}
}
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) {
for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) {
// Notify car
}
}
private static int sendOneTimeNotification() {
System.out.println("Sending one time notification!");
return 1;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) {
var x = cars.poll();
var y = cars.poll();
var z = cars.poll();
return x;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) {
var car = cars.poll();
var _ = cars.poll();
var _ = cars.poll();
return car;
}
static void handleCarExceptionWithNamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException ex) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException ex) {
System.out.println("Got a runtime exception!");
}
}
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException | NumberFormatException _) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException _) {
System.out.println("Got a runtime exception!");
}
}
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
try (var transaction = new Transaction()) {
updateCar(car);
}
}
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) {
updateCar(car);
}
}
static void updateCar(Car<?> car) {
// Some update logic
System.out.println("Car updated!");
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
);
return carMap;
}
private static void someOperationThatFails(Car<?> car) {
throw new IllegalStateException("Triggered exception for: " + car.name());
}
}
@@ -0,0 +1,3 @@
void main() {
System.out.println("Hello, World!");
}
@@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldChild extends HelloWorldSuper {
void main() {
System.out.println("Hello, World!");
}
}
@@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldSuper {
public static void main(String[] args) {
System.out.println("Hello from the superclass");
}
}
@@ -0,0 +1,6 @@
private String getMessage() {
return "Hello, World!";
}
void main() {
System.out.println(getMessage());
}
@@ -0,0 +1,13 @@
package com.baeldung.unnamed.variables;
import java.util.List;
class CarScenario {
protected final List<Car<?>> cars = List.of(
new Car<>("Mitsubishi", "blue", new GasEngine()),
new Car<>("Toyota", "red", new ElectricEngine()),
new Car<>("Jaguar", "white", new HybridEngine())
);
}
@@ -0,0 +1,44 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UnnamedPatternsUnitTest extends CarScenario {
@Test
public void whenExtractingColorWithNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0)));
}
}
@@ -0,0 +1,93 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
public class UnnamedVariablesUnitTest extends CarScenario {
@Test
public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2));
}
@Test
public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2));
}
@Test
public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars));
}
@Test
public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars));
}
@Test
public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
@Test
public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
}
@@ -4,3 +4,4 @@ This module contains articles about Java 9 streams
### Relevant Articles:
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
- [Creating Stream of Regex Matches](https://www.baeldung.com/java-stream-regex-matches)
@@ -9,3 +9,4 @@ This module contains complete guides about arrays in Java
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
@@ -0,0 +1,2 @@
## Relevant Articles
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
@@ -14,4 +14,3 @@ This module contains articles about advanced operations on arrays in Java. They
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)
@@ -0,0 +1,29 @@
package com.baeldung.incrementchar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class IncrementCharUnitTest {
@Test
void whenUsingForLoop_thenGenerateCharacters(){
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
List<Character> characters = new ArrayList<>();
for (char character = 'A'; character <= 'Z'; character++) {
characters.add(character);
}
Assertions.assertEquals(characters, allCapitalCharacters);
}
@Test
void whenUsingStreams_thenGenerateCharacters() {
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
final List<Character> characters = IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).collect(Collectors.toList());
Assertions.assertEquals(characters, allCapitalCharacters);
}
}
@@ -0,0 +1,126 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SkipFirstElementExample {
private final List<String> stringList = new ArrayList<>();
private final Set<String> stringSet = new HashSet<>();
private final Map<String, String> stringMap = new HashMap<>();
public SkipFirstElementExample() {
// Initializing a List
stringList.add("Monday");
stringList.add("Tuesday");
stringList.add("Wednesday");
stringList.add("Thursday");
stringList.add("Friday");
stringList.add("Saturday");
stringList.add("Sunday");
// Initializing a Set
stringSet.add("Monday");
stringSet.add("Tuesday");
stringSet.add("Wednesday");
stringSet.add("Thursday");
stringSet.add("Friday");
stringSet.add("Saturday");
stringSet.add("Sunday");
// Initializing a Map
stringMap.put("Monday", "The day when coffee is a life support system.");
stringMap.put("Tuesday", "The day you realize that Monday's optimism was a lie.");
stringMap.put("Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.");
stringMap.put("Thursday", "The day that says, 'Hold my beer, Friday is coming!'");
stringMap.put("Friday", "The golden child of the weekdays. The superhero of the workweek.");
stringMap.put("Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'");
stringMap.put("Sunday", "The day before you have to adult again.");
}
void skippingFirstElementInListWithForLoop(List<String> stringList) {
for (int i = 1; i < stringList.size(); i++) {
process(stringList.get(i));
}
}
void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
final Iterator<String> iterator = stringSet.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
String firstElement = null;
if (iterator.hasNext()) {
firstElement = iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
// additional logic using fistElement
}
}
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
stringMap.entrySet().stream().skip(1).forEach(this::process);
}
void skippingFirstElementInListWithSubList(List<String> stringList) {
for (final String element : stringList.subList(1, stringList.size())) {
process(element);
}
}
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
for (int i = 0; i < stringList.size(); i++) {
if (i == 0) {
// do something else
} else {
process(stringList.get(i));
}
}
}
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
int counter = 0;
while (counter < stringList.size()) {
if (counter != 0) {
process(stringList.get(counter));
}
++counter;
}
}
void skippingFirstElementInListWithReduce(List<String> stringList) {
stringList.stream().reduce((skip, element) -> {
process(element);
return element;
});
}
protected void process(String string) {
System.out.println(string);
}
protected void process(Entry<String, String> mapEntry) {
System.out.println(mapEntry);
}
}
@@ -0,0 +1,122 @@
package com.baeldung.skippingfirstelement;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@EnabledForJreRange(min = JRE.JAVA_9)
class SkipFirstElementExampleUnitTest {
private static TestableSkipFirstElement testableSkip = new TestableSkipFirstElement();
@BeforeEach
void setup() {
testableSkip.reset();
}
private static Stream<Arguments> listProvider() {
return Stream.of(
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
);
}
private static Stream<Arguments> mapProvider() {
return Stream.of(
Arguments.of(
Map.of(
"Monday", "The day when coffee is a life support system.",
"Tuesday", "The day you realize that Monday's optimism was a lie.",
"Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.",
"Thursday", "The day that says, 'Hold my beer, Friday is coming!'",
"Friday", "The golden child of the weekdays. The superhero of the workweek.",
"Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'",
"Sunday", "The day before you have to adult again."
)
)
);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInSetWithWhileLoop(List<String> input) {
testableSkip.skippingFirstElementInSetWithWhileLoop(new HashSet<>(input));
Set<?> actual = new HashSet<>(testableSkip.getResult());
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopStoringFirstElement(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("mapProvider")
void skippingFirstElementInMapWithStreamSkip(Map<String, String> input) {
testableSkip.skippingFirstElementInMapWithStreamSkip(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithSubList(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithSubList(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoopWithAdditionalCheck(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopWithCounter(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithReduce(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithReduce(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.skippingfirstelement;
import java.util.List;
public interface TestableSkip {
void reset();
List<?> getResult();
}
@@ -0,0 +1,37 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
public class TestableSkipFirstElement extends SkipFirstElementExample implements TestableSkip {
private List<String> processedList = new ArrayList<>();
private List<Entry<String, String>> processedEntryList = new ArrayList<>();
@Override
public void process(String string) {
processedList.add(string);
}
@Override
public void process(Entry<String, String> stringEntry) {
processedEntryList.add(stringEntry);
}
@Override
public void reset() {
processedList.clear();
processedEntryList.clear();
}
@Override
public List<?> getResult() {
if (!processedList.isEmpty())
return processedList;
return processedEntryList;
}
}
@@ -0,0 +1,6 @@
## Core Java Collections ArrayList
This module contains articles about the Java ArrayList collection
### Relevant Articles:
- [Create an ArrayList with Multiple Object Types](https://www.baeldung.com/arraylist-with-multiple-object-types)
@@ -0,0 +1,32 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-array-list-2</artifactId>
<name>core-java-collections-array-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
</properties>
</project>
@@ -0,0 +1,51 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Predicate;
public class AlternativeMultipeTypeList {
public static void main(String[] args) {
// List of Parent Class
ArrayList<Number> myList = new ArrayList<>();
myList.add(1.2);
myList.add(2);
myList.add(-3.5);
// List of Interface type
ArrayList<Map> diffMapList = new ArrayList<>();
diffMapList.add(new HashMap<>());
diffMapList.add(new TreeMap<>());
diffMapList.add(new LinkedHashMap<>());
// List of Custom Object
ArrayList<CustomObject> objList = new ArrayList<>();
objList.add(new CustomObject("String"));
objList.add(new CustomObject(2));
// List via Functional Interface
List<Object> dataList = new ArrayList<>();
Predicate<Object> myPredicate = inputData -> (inputData instanceof String || inputData instanceof Integer);
UserFunctionalInterface myInterface = (listObj, data) -> {
if (myPredicate.test(data))
listObj.add(data);
else
System.out.println("Skipping input as data not allowed for class: " + data.getClass()
.getSimpleName());
return listObj;
};
myInterface.addToList(dataList, Integer.valueOf(2));
myInterface.addToList(dataList, Double.valueOf(3.33));
myInterface.addToList(dataList, "String Value");
myInterface.printList(dataList);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.list.multipleobjecttypes;
public class CustomObject {
String classData;
Integer intData;
CustomObject(String classData) {
this.classData = classData;
}
CustomObject(Integer intData) {
this.intData = intData;
}
public String getClassData() {
return this.classData;
}
public Integer getIntData() {
return this.intData;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.list.multipleobjecttypes;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultipleObjectTypeArrayList {
public static void main(String[] args) {
ArrayList<Object> multiTypeList = new ArrayList<>();
multiTypeList.add(Integer.valueOf(10));
multiTypeList.add(Double.valueOf(11.5));
multiTypeList.add("String Data");
multiTypeList.add(Arrays.asList(1, 2, 3));
multiTypeList.add(new CustomObject("Class Data"));
multiTypeList.add(BigInteger.valueOf(123456789));
multiTypeList.add(LocalDate.of(2023, 9, 19));
for (Object dataObj : multiTypeList) {
if (dataObj instanceof Integer intData)
System.out.println("Integer Data : " + intData);
else if (dataObj instanceof Double doubleData)
System.out.println("Double Data : " + doubleData);
else if (dataObj instanceof String stringData)
System.out.println("String Data : " + stringData);
else if (dataObj instanceof List<?> intList)
System.out.println("List Data : " + intList);
else if (dataObj instanceof CustomObject customObj)
System.out.println("CustomObject Data : " + customObj.getClassData());
else if (dataObj instanceof BigInteger bigIntData)
System.out.println("BigInteger Data : " + bigIntData);
else if (dataObj instanceof LocalDate localDate)
System.out.println("LocalDate Data : " + localDate.toString());
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.List;
@FunctionalInterface
public interface UserFunctionalInterface {
List<Object> addToList(List<Object> list, Object data);
default void printList(List<Object> dataList) {
for (Object data : dataList) {
if (data instanceof String stringData)
System.out.println("String Data: " + stringData);
if (data instanceof Integer intData)
System.out.println("Integer Data: " + intData);
}
}
}

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