Merge branch 'master' into BAEL-6421-PrintWriter-write-vs-print

This commit is contained in:
Andrei Branza
2024-03-27 20:58:57 +02:00
222 changed files with 1327 additions and 285 deletions
@@ -0,0 +1,54 @@
package com.baeldung.immutables;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class ImmutableCollectionsUnitTest {
@Test
void givenUnmodifiableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() {
Map<String, String> modifiableMap = new HashMap<>();
modifiableMap.put("name1", "Michael");
modifiableMap.put("name2", "Harry");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("name3", "Micky"));
}
@Test
void givenUnmodifiableMap_whenPutNewEntryUsingOriginalReference_thenSuccess() {
Map<String, String> modifiableMap = new HashMap<>();
modifiableMap.put("name1", "Michael");
modifiableMap.put("name2", "Harry");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(modifiableMap);
modifiableMap.put("name3", "Micky");
assertEquals(modifiableMap, unmodifiableMap);
assertTrue(unmodifiableMap.containsKey("name3"));
}
@Test
void givenImmutableMap_whenPutNewEntry_thenThrowsUnsupportedOperationException() {
Map<String, String> immutableMap = Map.of("name1", "Michael", "name2", "Harry");
assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("name3", "Micky"));
}
@Test
void givenImmutableMap_whenUsecopyOf_thenExceptionOnPut() {
Map<String, String> immutableMap = Map.of("name1", "Michael", "name2", "Harry");
Map<String, String> copyOfImmutableMap = Map.copyOf(immutableMap);
assertThrows(UnsupportedOperationException.class, () -> copyOfImmutableMap.put("name3", "Micky"));
}
}
@@ -5,3 +5,4 @@
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
- [Reset ListIterator to First Element of the List in Java](https://www.baeldung.com/java-reset-listiterator)
- [Modify and Print List Items With Java Streams](https://www.baeldung.com/java-stream-list-update-print-elements)
- [Add One Element to an Immutable List in Java](https://www.baeldung.com/java-immutable-list-add-element)
@@ -0,0 +1,49 @@
package com.baeldung.addtoimmutablelist;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
public class AddElementsToImmutableListUnitTest {
public static <T> List<T> appendAnElement(List<T> immutableList, T element) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.add(element);
return Collections.unmodifiableList(tmpList);
}
@SafeVarargs
public static <T> List<T> appendElements(List<T> immutableList, T... elements) {
List<T> tmpList = new ArrayList<>(immutableList);
tmpList.addAll(Arrays.asList(elements));
return Collections.unmodifiableList(tmpList);
}
@Test
void whenCallingAppendAnElement_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected = List.of("A", "B", "C", "D", "E", "F");
List<String> result = appendAnElement(myList, "F");
assertThat(result).isEqualTo(expected)
.isUnmodifiable();
}
@Test
void whenCallingAppendElements_thenGetExpectedResult() {
List<String> myList = List.of("A", "B", "C", "D", "E");
List<String> expected1 = List.of("A", "B", "C", "D", "E", "F");
List<String> result1 = appendElements(myList, "F");
assertThat(result1).isEqualTo(expected1)
.isUnmodifiable();
List<String> expected2 = List.of("A", "B", "C", "D", "E", "F", "G", "H", "I");
List<String> result2 = appendElements(myList, "F", "G", "H", "I");
assertThat(result2).isEqualTo(expected2)
.isUnmodifiable();
}
}
@@ -10,5 +10,6 @@ This module contains articles about core Java input and output (IO)
- [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several)
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
- [Convert an OutputStream to a Byte Array in Java](https://www.baeldung.com/java-outputstream-byte-array)
- [Reading a .gz File Line by Line Using GZIPInputStream](https://www.baeldung.com/java-gzipinputstream-read-gz-file-line-by-line)
- [[<-- Prev]](/core-java-modules/core-java-io-4)
@@ -0,0 +1,73 @@
package com.baeldung.usinggzipInputstream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import static java.util.stream.Collectors.toList;
public class Main {
static String filePath = Objects.requireNonNull(Main.class.getClassLoader().getResource("myFile.gz")).getFile();
public static void main(String[] args) throws IOException {
// Test readGZipFile method
List<String> fileContents = readGZipFile(filePath);
System.out.println("Contents of GZIP file:");
fileContents.forEach(System.out::println);
// Test findInZipFile method
String searchTerm = "Line 1 content";
List<String> foundLines = findInZipFile(filePath, searchTerm);
System.out.println("Lines containing '" + searchTerm + "' in GZIP file:");
foundLines.forEach(System.out::println);
// Test useContentsOfZipFile method
System.out.println("Using contents of GZIP file with consumer:");
useContentsOfZipFile(filePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(System.out::println);
});
}
public static List<String> readGZipFile(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
public static List<String> findInZipFile(String filePath, String toFind) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
return bufferedReader.lines().filter(line -> line.contains(toFind)).collect(toList());
}
}
public static void useContentsOfZipFile(String filePath, Consumer<Stream<String>> consumer) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
consumer.accept(bufferedReader.lines());
}
}
}
@@ -0,0 +1,50 @@
package com.baeldung.usinggzipInputstream;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class ReadingGZIPUsingGZIPInputStreamUnitTest {
String testFilePath = Objects.requireNonNull(ReadingGZIPUsingGZIPInputStreamUnitTest.class.getClassLoader().getResource("myFile.gz")).getFile();
List<String> expectedFilteredLines = Arrays.asList("Line 1 content", "Line 2 content", "Line 3 content");
@Test
void givenGZFile_whenUsingGZIPInputStream_thenReadLines() throws IOException {
try (Stream<String> lines = Main.readGZipFile(testFilePath).stream()) {
List<String> result = lines
.filter(expectedFilteredLines::contains)
.collect(Collectors.toList());
assertEquals(expectedFilteredLines, result);
}
}
@Test
void givenGZFile_whenUsingtestFindInZipFile_thenReadLines() throws IOException {
String toFind = "Line 1 content";
List<String> result = Main.findInZipFile(testFilePath, toFind);
assertEquals("Line 1 content", result.get(0));
}
@Test
void givenGZFile_whenUsingContentsOfZipFile_thenReadLines() throws IOException {
AtomicInteger count = new AtomicInteger(0);
Main.useContentsOfZipFile(testFilePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(line -> count.incrementAndGet());
});
assertEquals(3, count.get());
}
}
@@ -72,4 +72,5 @@
<properties>
<junit-jupiter-version>5.9.3</junit-jupiter-version>
</properties>
</project>
</project>
@@ -0,0 +1,39 @@
package com.baeldung.inputstreamreader;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
public class InputStreamReaderUnitTest {
@Test
public void givenAStringWrittenToAFile_whenReadByInputStreamReader_thenShouldMatchWhenRead(@TempDir Path tempDir) throws IOException {
String sampleTxt = "Good day. This is just a test. Good bye.";
Path sampleOut = tempDir.resolve("sample-out.txt");
List<String> lines = Arrays.asList(sampleTxt);
Files.write(sampleOut, lines);
String absolutePath = String.valueOf(sampleOut.toAbsolutePath());
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(absolutePath), StandardCharsets.UTF_8)) {
boolean isMatched = false;
int b;
StringBuilder sb = new StringBuilder();
while ((b = reader.read()) != -1) {
sb.append((char) b);
if (sb.toString().contains(sampleTxt)) {
isMatched = true;
break;
}
}
assertThat(isMatched).isTrue();
}
}
}
@@ -4,4 +4,5 @@ This module contains article about constructors in Java
### Relevant Articles:
- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)
- [When to Use Setter Methods or Constructors for Setting a Variables Value in Java](https://www.baeldung.com/java-setter-method-vs-constructor)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)
@@ -0,0 +1,14 @@
package com.baeldung.statementsbeforesuper;
class Child extends Parent {
Child() {
super(); // Or super(10); Correct placements
System.out.println("Child constructor");
additionalInitialization();
// super(); Compilation error: Constructor call must be the first statement in a constructor
}
private void additionalInitialization() {
System.out.println("Additional initialization in Child");
}
}
@@ -0,0 +1,11 @@
package com.baeldung.statementsbeforesuper;
public class Parent {
public Parent(int id) {
System.out.println("Parametrized Parent constructor");
}
public Parent() {
System.out.println("Parent constructor");
}
}
@@ -49,7 +49,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@@ -73,6 +73,7 @@
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
<jacoco-maven-plugin.version>0.8.11</jacoco-maven-plugin.version>
</properties>
</project>
@@ -49,7 +49,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
@@ -73,6 +73,7 @@
<source.version>1.8</source.version>
<target.version>1.8</target.version>
<spring.version>5.3.4</spring.version>
<jacoco-maven-plugin.version>0.8.11</jacoco-maven-plugin.version>
</properties>
</project>
@@ -1,3 +1,4 @@
## Relevant Articles:
- [Handle Duplicate Keys When Producing Map Using Java Stream](https://www.baeldung.com/java-duplicate-keys-when-producing-map-using-stream)
- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap)
- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap)
- [Flatten a Stream of Maps to a Single Map in Java](https://www.baeldung.com/java-flatten-stream-map)
@@ -0,0 +1,143 @@
package com.baeldung.streams.mapstreamtomap;
import static java.lang.Math.max;
import static java.util.stream.Collectors.flatMapping;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.reducing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class MapStreamToMapUnitTest {
Map<String, Integer> playerMap1 = new HashMap<String, Integer>() {{
put("Kai", 92);
put("Liam", 100);
}};
Map<String, Integer> playerMap2 = new HashMap<String, Integer>() {{
put("Eric", 42);
put("Kevin", 77);
}};
Map<String, Integer> playerMap3 = new HashMap<String, Integer>() {{
put("Saajan", 35);
}};
Map<String, Integer> playerMap4 = new HashMap<String, Integer>() {{
put("Kai", 76);
}};
Map<String, Integer> playerMap5 = new HashMap<String, Integer>() {{
put("Kai", null);
put("Jerry", null);
}};
@Test
void givenMapsStream_whenUsingFlatMapAndToMap_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92);
put("Eric", 42);
put("Kevin", 77);
}};
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
assertEquals(expectedMap, mergedMap);
}
@Test
void givenMapsWithDuplicateKeys_whenUsingFlatMapAndToMap_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 76 and 92
put("Eric", 42);
put("Kevin", 77);
}};
assertThrows(IllegalStateException.class, () -> Stream.of(playerMap1, playerMap2, playerMap3, playerMap4)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), "Duplicate key Kai (attempted merging values 92 and 76)");
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3, playerMap4)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::max));
assertEquals(expectedMap, mergedMap);
}
private Integer maxInteger(Integer int1, Integer int2) {
if (int1 == null) {
return int2;
}
if (int2 == null) {
return int1;
}
return max(int1, int2);
}
@Test
void givenMapsWithDuplicateKeysAndNullValues_whenUsingFlatMapWithForEach_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 92, 76, and null
put("Eric", 42);
put("Kevin", 77);
put("Jerry", null);
}};
assertThrows(NullPointerException.class, () -> Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(map -> map.entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Integer::max)));
Map<String, Integer> mergedMap = new HashMap<>();
Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(map -> map.entrySet()
.stream())
.forEach(entry -> {
String k = entry.getKey();
Integer v = entry.getValue();
if (mergedMap.containsKey(k)) {
mergedMap.put(k, maxInteger(mergedMap.get(k), v));
} else {
mergedMap.put(k, v);
}
});
assertEquals(expectedMap, mergedMap);
}
@Test
void givenMapsWithDuplicateKeysAndNullValues_whenUsingReduce_thenMultipleMapsMergedIntoOneMap() {
Map<String, Integer> expectedMap = new HashMap<String, Integer>() {{
put("Saajan", 35);
put("Liam", 100);
put("Kai", 92); // max of 92, 76, and null
put("Eric", 42);
put("Kevin", 77);
put("Jerry", null);
}};
Map<String, Integer> mergedMap = Stream.of(playerMap1, playerMap2, playerMap3, playerMap4, playerMap5)
.flatMap(x -> x.entrySet()
.stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, reducing(null, this::maxInteger))));
assertEquals(expectedMap, mergedMap);
}
}
@@ -6,3 +6,5 @@
- [Get First n Characters in a String in Java](https://www.baeldung.com/get-first-n-characters-in-a-string-in-java)
- [Remove Only Trailing Spaces or Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-only-trailing-whitespace)
- [Get the Initials of a Name in Java](https://www.baeldung.com/java-shorten-name-initials)
- [Normalizing the EOL Character in Java](https://www.baeldung.com/java-normalize-end-of-line-character)
- [Converting UTF-8 to ISO-8859-1 in Java](https://www.baeldung.com/java-utf-8-iso-8859-1-conversion)